Skip to main content

rustc_borrowck/diagnostics/
opaque_types.rs

1use std::ops::ControlFlow;
2
3use either::Either;
4use itertools::Itertools as _;
5use rustc_data_structures::fx::FxIndexSet;
6use rustc_errors::{Diag, Subdiagnostic};
7use rustc_hir as hir;
8use rustc_hir::def_id::DefId;
9use rustc_middle::mir::{self, ConstraintCategory, Location};
10use rustc_middle::ty::{
11    self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor,
12    Unnormalized,
13};
14use rustc_span::Span;
15use rustc_trait_selection::diagnostics::impl_trait_overcapture_suggestion;
16use rustc_trait_selection::error_reporting::infer::region::unexpected_hidden_region_diagnostic;
17
18use crate::MirBorrowckCtxt;
19use crate::borrow_set::BorrowData;
20use crate::consumers::RegionInferenceContext;
21use crate::region_infer::opaque_types::DeferredOpaqueTypeError;
22use crate::type_check::Locations;
23
24impl<'infcx, 'tcx> MirBorrowckCtxt<'_, 'infcx, 'tcx> {
25    pub(crate) fn report_opaque_type_errors(&mut self, errors: Vec<DeferredOpaqueTypeError<'tcx>>) {
26        if errors.is_empty() {
27            return;
28        }
29
30        let infcx = self.infcx;
31        let mut last_unexpected_hidden_region: Option<(Span, Ty<'_>, ty::OpaqueTypeKey<'tcx>)> =
32            None;
33        for error in errors {
34            match error {
35                DeferredOpaqueTypeError::InvalidOpaqueTypeArgs(err) => err.report(infcx),
36                DeferredOpaqueTypeError::LifetimeMismatchOpaqueParam(err) => {
37                    infcx.dcx().emit_err(err)
38                }
39                DeferredOpaqueTypeError::UnexpectedHiddenRegion {
40                    opaque_type_key,
41                    hidden_type,
42                    member_region,
43                } => {
44                    let named_ty =
45                        self.regioncx.name_regions_for_member_constraint(infcx.tcx, hidden_type.ty);
46                    let named_key = self
47                        .regioncx
48                        .name_regions_for_member_constraint(infcx.tcx, opaque_type_key);
49                    let named_region =
50                        self.regioncx.name_regions_for_member_constraint(infcx.tcx, member_region);
51                    let diag = unexpected_hidden_region_diagnostic(
52                        infcx,
53                        self.mir_def_id(),
54                        hidden_type.span,
55                        named_ty,
56                        named_region,
57                        named_key,
58                    );
59                    if last_unexpected_hidden_region
60                        != Some((hidden_type.span, named_ty, named_key))
61                    {
62                        last_unexpected_hidden_region =
63                            Some((hidden_type.span, named_ty, named_key));
64                        diag.emit()
65                    } else {
66                        diag.delay_as_bug()
67                    }
68                }
69                DeferredOpaqueTypeError::NonDefiningUseInDefiningScope {
70                    span,
71                    opaque_type_key,
72                } => infcx.dcx().span_err(
73                    span,
74                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("non-defining use of `{0}` in the defining scope",
                Ty::new_opaque(infcx.tcx, ty::IsRigid::No,
                    opaque_type_key.def_id.to_def_id(), opaque_type_key.args)))
    })format!(
75                        "non-defining use of `{}` in the defining scope",
76                        Ty::new_opaque(
77                            infcx.tcx,
78                            ty::IsRigid::No,
79                            opaque_type_key.def_id.to_def_id(),
80                            opaque_type_key.args
81                        )
82                    ),
83                ),
84            };
85        }
86    }
87
88    /// Try to note when an opaque is involved in a borrowck error and that
89    /// opaque captures lifetimes due to edition 2024.
90    // FIXME: This code is otherwise somewhat general, and could easily be adapted
91    // to explain why other things overcapture... like async fn and RPITITs.
92    pub(crate) fn note_due_to_edition_2024_opaque_capture_rules(
93        &self,
94        borrow: &BorrowData<'tcx>,
95        diag: &mut Diag<'_>,
96    ) {
97        // We look at all the locals. Why locals? Because it's the best thing
98        // I could think of that's correlated with the *instantiated* higher-ranked
99        // binder for calls, since we don't really store those anywhere else.
100        for ty in self.body.local_decls.iter().map(|local| local.ty) {
101            if !ty.has_opaque_types() {
102                continue;
103            }
104
105            let tcx = self.infcx.tcx;
106            let ControlFlow::Break((opaque_def_id, offending_region_idx, location)) = ty
107                .visit_with(&mut FindOpaqueRegion {
108                    regioncx: &self.regioncx,
109                    tcx,
110                    borrow_region: borrow.region,
111                })
112            else {
113                continue;
114            };
115
116            // If an opaque explicitly captures a lifetime, then no need to point it out.
117            // FIXME: We should be using a better heuristic for `use<>`.
118            if tcx.rendered_precise_capturing_args(opaque_def_id).is_some() {
119                continue;
120            }
121
122            // If one of the opaque's bounds mentions the region, then no need to
123            // point it out, since it would've been captured on edition 2021 as well.
124            //
125            // Also, while we're at it, collect all the lifetimes that the opaque
126            // *does* mention. We'll use that for the `+ use<'a>` suggestion below.
127            let mut visitor = CheckExplicitRegionMentionAndCollectGenerics {
128                tcx,
129                generics: tcx.generics_of(opaque_def_id),
130                offending_region_idx,
131                seen_opaques: [opaque_def_id].into_iter().collect(),
132                seen_lifetimes: Default::default(),
133            };
134            if tcx
135                .explicit_item_bounds(opaque_def_id)
136                .skip_binder()
137                .visit_with(&mut visitor)
138                .is_break()
139            {
140                continue;
141            }
142
143            // If we successfully located a terminator, then point it out
144            // and provide a suggestion if it's local.
145            match self.body.stmt_at(location) {
146                Either::Right(mir::Terminator { source_info, .. }) => {
147                    diag.span_note(
148                        source_info.span,
149                        "this call may capture more lifetimes than intended, \
150                        because Rust 2024 has adjusted the `impl Trait` lifetime capture rules",
151                    );
152                    let mut captured_args = visitor.seen_lifetimes;
153                    // Add in all of the type and const params, too.
154                    // Ordering here is kinda strange b/c we're walking backwards,
155                    // but we're trying to provide *a* suggestion, not a nice one.
156                    let mut next_generics = Some(visitor.generics);
157                    let mut any_synthetic = false;
158                    while let Some(generics) = next_generics {
159                        for param in &generics.own_params {
160                            if param.kind.is_ty_or_const() {
161                                captured_args.insert(param.def_id);
162                            }
163                            if param.kind.is_synthetic() {
164                                any_synthetic = true;
165                            }
166                        }
167                        next_generics = generics.parent.map(|def_id| tcx.generics_of(def_id));
168                    }
169
170                    if let Some(opaque_def_id) = opaque_def_id.as_local()
171                        && let hir::OpaqueTyOrigin::FnReturn { parent, .. } =
172                            tcx.hir_expect_opaque_ty(opaque_def_id).origin
173                    {
174                        if let Some(sugg) = impl_trait_overcapture_suggestion(
175                            tcx,
176                            opaque_def_id,
177                            parent,
178                            captured_args,
179                        ) {
180                            sugg.add_to_diag(diag);
181                        }
182                    } else {
183                        diag.span_help(
184                            tcx.def_span(opaque_def_id),
185                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("if you can modify this crate, add a precise capturing bound to avoid overcapturing: `+ use<{0}>`",
                if any_synthetic {
                    "/* Args */".to_string()
                } else {
                    captured_args.into_iter().map(|def_id|
                                tcx.item_name(def_id)).join(", ")
                }))
    })format!(
186                                "if you can modify this crate, add a precise \
187                                capturing bound to avoid overcapturing: `+ use<{}>`",
188                                if any_synthetic {
189                                    "/* Args */".to_string()
190                                } else {
191                                    captured_args
192                                        .into_iter()
193                                        .map(|def_id| tcx.item_name(def_id))
194                                        .join(", ")
195                                }
196                            ),
197                        );
198                    }
199                    return;
200                }
201                Either::Left(_) => {}
202            }
203        }
204    }
205}
206
207/// This visitor contains the bulk of the logic for this lint.
208struct FindOpaqueRegion<'a, 'tcx> {
209    tcx: TyCtxt<'tcx>,
210    regioncx: &'a RegionInferenceContext<'tcx>,
211    borrow_region: ty::RegionVid,
212}
213
214impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for FindOpaqueRegion<'_, 'tcx> {
215    type Result = ControlFlow<(DefId, usize, Location), ()>;
216
217    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
218        // If we find an opaque in a local ty, then for each of its captured regions,
219        // try to find a path between that captured regions and our borrow region...
220        if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) = *ty.kind()
221            && let hir::OpaqueTyOrigin::FnReturn { parent, in_trait_or_impl: None } =
222                self.tcx.opaque_ty_origin(def_id)
223        {
224            let variances = self.tcx.variances_of(def_id);
225            for (idx, (arg, variance)) in std::iter::zip(args, variances).enumerate() {
226                // Skip uncaptured args.
227                if *variance == ty::Bivariant {
228                    continue;
229                }
230                // We only care about regions.
231                let Some(opaque_region) = arg.as_region() else {
232                    continue;
233                };
234                // Don't try to convert a late-bound region, which shouldn't exist anyways (yet).
235                if opaque_region.is_bound() {
236                    continue;
237                }
238                let opaque_region_vid = self.regioncx.to_region_vid(opaque_region);
239
240                // Find a path between the borrow region and our opaque capture.
241                if let Some(path) = self
242                    .regioncx
243                    .constraint_path_between_regions(self.borrow_region, opaque_region_vid)
244                {
245                    for constraint in path {
246                        // If we find a call in this path, then check if it defines the opaque.
247                        if let ConstraintCategory::CallArgument(Some(call_ty)) = constraint.category
248                            && let ty::FnDef(call_def_id, _) = *call_ty.kind()
249                            // This function defines the opaque :D
250                            && call_def_id == parent
251                            && let Locations::Single(location) = constraint.locations
252                        {
253                            return ControlFlow::Break((def_id, idx, location));
254                        }
255                    }
256                }
257            }
258        }
259
260        ty.super_visit_with(self)
261    }
262}
263
264struct CheckExplicitRegionMentionAndCollectGenerics<'tcx> {
265    tcx: TyCtxt<'tcx>,
266    generics: &'tcx ty::Generics,
267    offending_region_idx: usize,
268    seen_opaques: FxIndexSet<DefId>,
269    seen_lifetimes: FxIndexSet<DefId>,
270}
271
272impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for CheckExplicitRegionMentionAndCollectGenerics<'tcx> {
273    type Result = ControlFlow<(), ()>;
274
275    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
276        match *ty.kind() {
277            ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
278                if self.seen_opaques.insert(def_id) {
279                    for (bound, _) in self
280                        .tcx
281                        .explicit_item_bounds(def_id)
282                        .iter_instantiated_copied(self.tcx, args)
283                        .map(Unnormalized::skip_norm_wip)
284                    {
285                        bound.visit_with(self)?;
286                    }
287                }
288                ControlFlow::Continue(())
289            }
290            _ => ty.super_visit_with(self),
291        }
292    }
293
294    fn visit_region(&mut self, r: ty::Region<'tcx>) -> Self::Result {
295        match r.kind() {
296            ty::ReEarlyParam(param) => {
297                if param.index as usize == self.offending_region_idx {
298                    ControlFlow::Break(())
299                } else {
300                    self.seen_lifetimes.insert(self.generics.region_param(param, self.tcx).def_id);
301                    ControlFlow::Continue(())
302                }
303            }
304            _ => ControlFlow::Continue(()),
305        }
306    }
307}