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