Skip to main content

rustc_hir_analysis/check/compare_impl_item/
refine.rs

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