Skip to main content

rustc_hir_analysis/check/compare_impl_item/
refine.rs

1use itertools::Itertools as _;
2use rustc_data_structures::fx::FxIndexSet;
3use rustc_hir as hir;
4use rustc_hir::def_id::{DefId, LocalDefId};
5use rustc_infer::infer::TyCtxtInferExt;
6use rustc_lint_defs::builtin::{REFINING_IMPL_TRAIT_INTERNAL, REFINING_IMPL_TRAIT_REACHABLE};
7use rustc_middle::span_bug;
8use rustc_middle::traits::ObligationCause;
9use rustc_middle::ty::print::{with_no_trimmed_paths, with_types_for_signature};
10use rustc_middle::ty::{
11    self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperVisitable, TypeVisitable,
12    TypeVisitableExt, TypeVisitor, TypingMode, Unnormalized,
13};
14use rustc_span::Span;
15use rustc_span::def_id::ModId;
16use rustc_trait_selection::regions::InferCtxtRegionExt;
17use rustc_trait_selection::traits::{ObligationCtxt, elaborate, normalize_param_env_or_error};
18
19/// Check that an implementation does not refine an RPITIT from a trait method signature.
20pub(crate) fn check_refining_return_position_impl_trait_in_trait<'tcx>(
21    tcx: TyCtxt<'tcx>,
22    impl_m: ty::AssocItem,
23    trait_m: ty::AssocItem,
24    impl_trait_ref: ty::TraitRef<'tcx>,
25) {
26    if !tcx.impl_method_has_trait_impl_trait_tys(impl_m.def_id) {
27        return;
28    }
29
30    // unreachable traits don't have any library guarantees, there's no need to do this check.
31    let is_internal = trait_m
32        .container_id(tcx)
33        .as_local()
34        .is_some_and(|trait_def_id| !tcx.effective_visibilities(()).is_reachable(trait_def_id))
35        // If a type in the trait ref is private, then there's also no reason to do this check.
36        || impl_trait_ref.args.iter().any(|arg| {
37            if let Some(ty) = arg.as_type()
38                && let Some(self_visibility) = type_visibility(tcx, ty)
39            {
40                return !self_visibility.is_public();
41            }
42            false
43        });
44
45    let impl_def_id = impl_m.container_id(tcx);
46    let impl_m_args = ty::GenericArgs::identity_for_item(tcx, impl_m.def_id);
47    let trait_m_to_impl_m_args = impl_m_args.rebase_onto(tcx, impl_def_id, impl_trait_ref.args);
48    let bound_trait_m_sig =
49        tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_to_impl_m_args).skip_norm_wip();
50    let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, bound_trait_m_sig);
51    // replace the self type of the trait ref with `Self` so that diagnostics render better.
52    let trait_m_sig_with_self_for_diag = tcx.liberate_late_bound_regions(
53        impl_m.def_id,
54        tcx.fn_sig(trait_m.def_id)
55            .instantiate(
56                tcx,
57                tcx.mk_args_from_iter(
58                    [tcx.types.self_param.into()]
59                        .into_iter()
60                        .chain(trait_m_to_impl_m_args.iter().skip(1)),
61                ),
62            )
63            .skip_norm_wip(),
64    );
65
66    let Ok(hidden_tys) = tcx.collect_return_position_impl_trait_in_trait_tys(impl_m.def_id) else {
67        // Error already emitted, no need to delay another.
68        return;
69    };
70
71    if hidden_tys.items().any(|(_, &ty)| ty.skip_binder().references_error()) {
72        return;
73    }
74
75    let mut collector = ImplTraitInTraitCollector { tcx, types: FxIndexSet::default() };
76    trait_m_sig.visit_with(&mut collector);
77
78    // Bound that we find on RPITITs in the trait signature.
79    let mut trait_bounds = ::alloc::vec::Vec::new()vec![];
80    // Bounds that we find on the RPITITs in the impl signature.
81    let mut impl_bounds = ::alloc::vec::Vec::new()vec![];
82    // Pairs of trait and impl opaques.
83    let mut pairs = ::alloc::vec::Vec::new()vec![];
84
85    for trait_projection in collector.types.into_iter().rev() {
86        let impl_opaque_args = trait_projection.args.rebase_onto(tcx, trait_m.def_id, impl_m_args);
87        let hidden_ty =
88            hidden_tys[&trait_projection.kind].instantiate(tcx, impl_opaque_args).skip_norm_wip();
89
90        // If the hidden type is not an opaque, then we have "refined" the trait signature.
91        let impl_opaque = if let ty::Alias(_, alias) = *hidden_ty.kind()
92            && let Some(impl_opaque) = alias.try_to_opaque()
93        {
94            impl_opaque
95        } else {
96            report_mismatched_rpitit_signature(
97                tcx,
98                trait_m_sig_with_self_for_diag,
99                trait_m.def_id,
100                impl_m.def_id,
101                None,
102                is_internal,
103            );
104            return;
105        };
106
107        // This opaque also needs to be from the impl method -- otherwise,
108        // it's a refinement to a TAIT.
109        if !tcx.hir_get_if_local(impl_opaque.kind).is_some_and(|node| {
110            #[allow(non_exhaustive_omitted_patterns)] match node.expect_opaque_ty().origin
    {
    hir::OpaqueTyOrigin::AsyncFn { parent, .. } |
        hir::OpaqueTyOrigin::FnReturn { parent, .. } if
        parent == impl_m.def_id.expect_local() => true,
    _ => false,
}matches!(
111                node.expect_opaque_ty().origin,
112                hir::OpaqueTyOrigin::AsyncFn { parent, .. }  | hir::OpaqueTyOrigin::FnReturn { parent, .. }
113                    if parent == impl_m.def_id.expect_local()
114            )
115        }) {
116            report_mismatched_rpitit_signature(
117                tcx,
118                trait_m_sig_with_self_for_diag,
119                trait_m.def_id,
120                impl_m.def_id,
121                None,
122                is_internal,
123            );
124            return;
125        }
126
127        trait_bounds.extend(
128            tcx.item_bounds(trait_projection.kind)
129                .iter_instantiated(tcx, trait_projection.args)
130                .map(Unnormalized::skip_norm_wip),
131        );
132        impl_bounds.extend(elaborate(
133            tcx,
134            tcx.explicit_item_bounds(impl_opaque.kind)
135                .iter_instantiated_copied(tcx, impl_opaque.args)
136                .map(Unnormalized::skip_norm_wip),
137        ));
138
139        pairs.push((trait_projection, impl_opaque));
140    }
141
142    let hybrid_preds = tcx
143        .predicates_of(impl_def_id)
144        .instantiate_identity(tcx)
145        .into_iter()
146        .chain(tcx.predicates_of(trait_m.def_id).instantiate_own(tcx, trait_m_to_impl_m_args))
147        .map(|(clause, _)| clause.skip_norm_wip());
148    let param_env = ty::ParamEnv::new(tcx.mk_clauses_from_iter(hybrid_preds));
149    let param_env = normalize_param_env_or_error(tcx, param_env, ObligationCause::dummy());
150
151    let ref infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
152    let ocx = ObligationCtxt::new(infcx);
153
154    // Normalize the bounds. This has two purposes:
155    //
156    // 1. Project the RPITIT projections from the trait to the opaques on the impl,
157    //    which means that they don't need to be mapped manually.
158    //
159    // 2. Deeply normalize any other projections that show up in the bound. That makes sure
160    //    that we don't consider `tests/ui/async-await/in-trait/async-associated-types.rs`
161    //    or `tests/ui/impl-trait/in-trait/refine-normalize.rs` to be refining.
162    let Ok((trait_bounds, impl_bounds)) = ocx.deeply_normalize(
163        &ObligationCause::dummy(),
164        param_env,
165        Unnormalized::new_wip((trait_bounds, impl_bounds)),
166    ) else {
167        tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (selection)");
168        return;
169    };
170
171    // Since we've normalized things, we need to resolve regions, since we'll
172    // possibly have introduced region vars during projection. We don't expect
173    // this resolution to have incurred any region errors -- but if we do, then
174    // just delay a bug.
175    let mut implied_wf_types = FxIndexSet::default();
176    implied_wf_types.extend(trait_m_sig.inputs_and_output);
177    implied_wf_types.extend(ocx.normalize(
178        &ObligationCause::dummy(),
179        param_env,
180        Unnormalized::new_wip(trait_m_sig.inputs_and_output),
181    ));
182    if !ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
183        tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (selection)");
184        return;
185    }
186    let errors = infcx.resolve_regions(impl_m.def_id.expect_local(), param_env, implied_wf_types);
187    if !errors.is_empty() {
188        tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (regions)");
189        return;
190    }
191    // Resolve any lifetime variables that may have been introduced during normalization.
192    let Ok((trait_bounds, impl_bounds)) = infcx.fully_resolve((trait_bounds, impl_bounds)) else {
193        // If resolution didn't fully complete, we cannot continue checking RPITIT refinement, and
194        // delay a bug as the original code contains load-bearing errors.
195        tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (resolution)");
196        return;
197    };
198
199    if trait_bounds.references_error() || impl_bounds.references_error() {
200        return;
201    }
202
203    // For quicker lookup, use an `IndexSet` (we don't use one earlier because
204    // it's not foldable..).
205    // Also, We have to anonymize binders in these types because they may contain
206    // `BrNamed` bound vars, which contain unique `DefId`s which correspond to syntax
207    // locations that we don't care about when checking bound equality.
208    let trait_bounds = FxIndexSet::from_iter(trait_bounds.fold_with(&mut Anonymize { tcx }));
209    let impl_bounds = impl_bounds.fold_with(&mut Anonymize { tcx });
210
211    // Find any clauses that are present in the impl's RPITITs that are not
212    // present in the trait's RPITITs. This will trigger on trivial predicates,
213    // too, since we *do not* use the trait solver to prove that the RPITIT's
214    // bounds are not stronger -- we're doing a simple, syntactic compatibility
215    // check between bounds. This is strictly forwards compatible, though.
216    for (clause, span) in impl_bounds {
217        if !trait_bounds.contains(&clause) {
218            report_mismatched_rpitit_signature(
219                tcx,
220                trait_m_sig_with_self_for_diag,
221                trait_m.def_id,
222                impl_m.def_id,
223                Some(span),
224                is_internal,
225            );
226            return;
227        }
228    }
229
230    // Make sure that the RPITIT doesn't capture fewer regions than
231    // the trait definition. We hard-error if it captures *more*, since that
232    // is literally unrepresentable in the type system; however, we may be
233    // promising stronger outlives guarantees if we capture *fewer* regions.
234    for (trait_projection, impl_opaque) in pairs {
235        let impl_variances = tcx.variances_of(impl_opaque.kind);
236        let impl_captures: FxIndexSet<_> = impl_opaque
237            .args
238            .iter()
239            .zip_eq(impl_variances)
240            .filter(|(_, v)| **v == ty::Invariant)
241            .map(|(arg, _)| arg)
242            .collect();
243
244        let trait_variances = tcx.variances_of(trait_projection.kind);
245        let mut trait_captures = FxIndexSet::default();
246        for (arg, variance) in trait_projection.args.iter().zip_eq(trait_variances) {
247            if *variance != ty::Invariant {
248                continue;
249            }
250            arg.visit_with(&mut CollectParams { params: &mut trait_captures });
251        }
252
253        if !trait_captures.iter().all(|arg| impl_captures.contains(arg)) {
254            report_mismatched_rpitit_captures(
255                tcx,
256                impl_opaque.kind.expect_local(),
257                trait_captures,
258                is_internal,
259            );
260        }
261    }
262}
263
264struct ImplTraitInTraitCollector<'tcx> {
265    tcx: TyCtxt<'tcx>,
266    types: FxIndexSet<ty::ProjectionAliasTy<'tcx>>,
267}
268
269impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'tcx> {
270    fn visit_ty(&mut self, ty: Ty<'tcx>) {
271        if let ty::Alias(_, alias) = *ty.kind()
272            && let Some(proj) = alias.try_to_projection()
273            && self.tcx.is_impl_trait_in_trait(proj.kind)
274        {
275            if self.types.insert(proj) {
276                for (pred, _) in self
277                    .tcx
278                    .explicit_item_bounds(proj.kind)
279                    .iter_instantiated_copied(self.tcx, proj.args)
280                    .map(Unnormalized::skip_norm_wip)
281                {
282                    pred.visit_with(self);
283                }
284            }
285        } else {
286            ty.super_visit_with(self);
287        }
288    }
289}
290
291fn report_mismatched_rpitit_signature<'tcx>(
292    tcx: TyCtxt<'tcx>,
293    trait_m_sig: ty::FnSig<'tcx>,
294    trait_m_def_id: DefId,
295    impl_m_def_id: DefId,
296    unmatched_bound: Option<Span>,
297    is_internal: bool,
298) {
299    let mapping = std::iter::zip(
300        tcx.fn_sig(trait_m_def_id).skip_binder().bound_vars(),
301        tcx.fn_sig(impl_m_def_id).skip_binder().bound_vars(),
302    )
303    .enumerate()
304    .filter_map(|(idx, (impl_bv, trait_bv))| {
305        if let ty::BoundVariableKind::Region(impl_bv) = impl_bv
306            && let ty::BoundVariableKind::Region(trait_bv) = trait_bv
307        {
308            let var = ty::BoundVar::from_usize(idx);
309            Some((
310                ty::LateParamRegionKind::from_bound(var, impl_bv),
311                ty::LateParamRegionKind::from_bound(var, trait_bv),
312            ))
313        } else {
314            None
315        }
316    })
317    .collect();
318
319    let mut return_ty = trait_m_sig.output().fold_with(&mut super::RemapLateParam { tcx, mapping });
320
321    if tcx.asyncness(impl_m_def_id).is_async() && tcx.asyncness(trait_m_def_id).is_async() {
322        let &ty::Alias(
323            _,
324            ty::AliasTy { kind: ty::Projection { def_id: future_ty_def_id }, args, .. },
325        ) = return_ty.kind()
326        else {
327            ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(trait_m_def_id),
    format_args!("expected return type of async fn in trait to be a AFIT projection"));span_bug!(
328                tcx.def_span(trait_m_def_id),
329                "expected return type of async fn in trait to be a AFIT projection"
330            );
331        };
332        let Some(future_output_ty) = tcx
333            .explicit_item_bounds(future_ty_def_id)
334            .iter_instantiated_copied(tcx, args)
335            .map(Unnormalized::skip_norm_wip)
336            .find_map(|(clause, _)| match clause.kind().no_bound_vars()? {
337                ty::ClauseKind::Projection(proj) => proj.term.as_type(),
338                _ => None,
339            })
340        else {
341            ::rustc_middle::util::bug::span_bug_fmt(tcx.def_span(trait_m_def_id),
    format_args!("expected `Future` projection bound in AFIT"));span_bug!(tcx.def_span(trait_m_def_id), "expected `Future` projection bound in AFIT");
342        };
343        return_ty = future_output_ty;
344    }
345
346    let (span, impl_return_span, pre, post) =
347        match tcx.hir_node_by_def_id(impl_m_def_id.expect_local()).fn_decl().unwrap().output {
348            hir::FnRetTy::DefaultReturn(span) => (tcx.def_span(impl_m_def_id), span, "-> ", " "),
349            hir::FnRetTy::Return(ty) => (ty.span, ty.span, "", ""),
350        };
351    let trait_return_span =
352        tcx.hir_get_if_local(trait_m_def_id).map(|node| match node.fn_decl().unwrap().output {
353            hir::FnRetTy::DefaultReturn(_) => tcx.def_span(trait_m_def_id),
354            hir::FnRetTy::Return(ty) => ty.span,
355        });
356
357    // Use ForSignature mode to ensure RPITITs are printed as `impl Trait` rather than
358    // `impl Trait { T::method(..) }` when RTN is enabled.
359    //
360    // We use `with_no_trimmed_paths!` to avoid triggering the `trimmed_def_paths` query,
361    // which requires diagnostic context (via `must_produce_diag`). Since we're formatting
362    // the type before creating the diagnostic, we need to avoid this query. This is the
363    // standard approach used elsewhere in the compiler for formatting types in suggestions
364    // (e.g., see `rustc_hir_typeck/src/demand.rs`).
365    let return_ty_suggestion =
366        {
    let _guard = NoTrimmedGuard::new();
    {
        let _guard =
            ::rustc_middle::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSignature);
        ::alloc::__export::must_use({
                ::alloc::fmt::format(format_args!("{0}", return_ty))
            })
    }
}with_no_trimmed_paths!(with_types_for_signature!(format!("{return_ty}")));
367
368    let span = unmatched_bound.unwrap_or(span);
369    tcx.emit_node_span_lint(
370        if is_internal { REFINING_IMPL_TRAIT_INTERNAL } else { REFINING_IMPL_TRAIT_REACHABLE },
371        tcx.local_def_id_to_hir_id(impl_m_def_id.expect_local()),
372        span,
373        crate::diagnostics::ReturnPositionImplTraitInTraitRefined {
374            impl_return_span,
375            trait_return_span,
376            pre,
377            post,
378            return_ty: return_ty_suggestion,
379            unmatched_bound,
380        },
381    );
382}
383
384fn type_visibility<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<ty::Visibility<ModId>> {
385    match *ty.kind() {
386        ty::Ref(_, ty, _) => type_visibility(tcx, ty),
387        ty::Adt(def, args) => {
388            if def.is_fundamental() {
389                type_visibility(tcx, args.type_at(0))
390            } else {
391                Some(tcx.visibility(def.did()))
392            }
393        }
394        _ => None,
395    }
396}
397
398struct Anonymize<'tcx> {
399    tcx: TyCtxt<'tcx>,
400}
401
402impl<'tcx> TypeFolder<TyCtxt<'tcx>> for Anonymize<'tcx> {
403    fn cx(&self) -> TyCtxt<'tcx> {
404        self.tcx
405    }
406
407    fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
408    where
409        T: TypeFoldable<TyCtxt<'tcx>>,
410    {
411        self.tcx.anonymize_bound_vars(t)
412    }
413}
414
415struct CollectParams<'a, 'tcx> {
416    params: &'a mut FxIndexSet<ty::GenericArg<'tcx>>,
417}
418impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for CollectParams<'_, 'tcx> {
419    fn visit_ty(&mut self, ty: Ty<'tcx>) {
420        if let ty::Param(_) = ty.kind() {
421            self.params.insert(ty.into());
422        } else {
423            ty.super_visit_with(self);
424        }
425    }
426    fn visit_region(&mut self, r: ty::Region<'tcx>) {
427        match r.kind() {
428            ty::ReEarlyParam(_) | ty::ReLateParam(_) => {
429                self.params.insert(r.into());
430            }
431            _ => {}
432        }
433    }
434    fn visit_const(&mut self, ct: ty::Const<'tcx>) {
435        if let ty::ConstKind::Param(_) = ct.kind() {
436            self.params.insert(ct.into());
437        } else {
438            ct.super_visit_with(self);
439        }
440    }
441}
442
443fn report_mismatched_rpitit_captures<'tcx>(
444    tcx: TyCtxt<'tcx>,
445    impl_opaque_def_id: LocalDefId,
446    mut trait_captured_args: FxIndexSet<ty::GenericArg<'tcx>>,
447    is_internal: bool,
448) {
449    let Some(use_bound_span) =
450        tcx.hir_node_by_def_id(impl_opaque_def_id).expect_opaque_ty().bounds.iter().find_map(
451            |bound| match *bound {
452                rustc_hir::GenericBound::Use(_, span) => Some(span),
453                hir::GenericBound::Trait(_) | hir::GenericBound::Outlives(_) => None,
454            },
455        )
456    else {
457        // I have no idea when you would ever undercapture without a `use<..>`.
458        tcx.dcx().delayed_bug("expected use<..> to undercapture in an impl opaque");
459        return;
460    };
461
462    trait_captured_args
463        .sort_by_cached_key(|arg| !#[allow(non_exhaustive_omitted_patterns)] match arg.kind() {
    ty::GenericArgKind::Lifetime(_) => true,
    _ => false,
}matches!(arg.kind(), ty::GenericArgKind::Lifetime(_)));
464    let suggestion = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use<{0}>",
                trait_captured_args.iter().join(", ")))
    })format!("use<{}>", trait_captured_args.iter().join(", "));
465
466    tcx.emit_node_span_lint(
467        if is_internal { REFINING_IMPL_TRAIT_INTERNAL } else { REFINING_IMPL_TRAIT_REACHABLE },
468        tcx.local_def_id_to_hir_id(impl_opaque_def_id),
469        use_bound_span,
470        crate::diagnostics::ReturnPositionImplTraitInTraitRefinedLifetimes {
471            suggestion_span: use_bound_span,
472            suggestion,
473        },
474    );
475}