rustc_hir_analysis/check/compare_impl_item/
refine.rs1use 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, TypeSuperFoldable, TypeSuperVisitable,
13 TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Unnormalized,
14};
15use rustc_span::def_id::ModId;
16use rustc_span::{Span, span_bug};
17use rustc_trait_selection::error_reporting::traits::suggest_new_overflow_limit;
18use rustc_trait_selection::regions::InferCtxtRegionExt;
19use rustc_trait_selection::traits::{ObligationCtxt, elaborate, normalize_param_env_or_error};
20
21pub(crate) fn check_refining_return_position_impl_trait_in_trait<'tcx>(
23 tcx: TyCtxt<'tcx>,
24 impl_m: ty::AssocItem,
25 trait_m: ty::AssocItem,
26 impl_trait_ref: ty::TraitRef<'tcx>,
27) {
28 if !tcx.impl_method_has_trait_impl_trait_tys(impl_m.def_id) {
29 return;
30 }
31
32 let is_internal = trait_m
34 .container_id(tcx)
35 .as_local()
36 .is_some_and(|trait_def_id| !tcx.effective_visibilities(()).is_reachable(trait_def_id))
37 || impl_trait_ref.args.iter().any(|arg| {
39 if let Some(ty) = arg.as_type()
40 && let Some(self_visibility) = type_visibility(tcx, ty)
41 {
42 return !self_visibility.is_public();
43 }
44 false
45 });
46
47 let impl_def_id = impl_m.container_id(tcx);
48 let impl_m_args = ty::GenericArgs::identity_for_item(tcx, impl_m.def_id);
49 let trait_m_to_impl_m_args = impl_m_args.rebase_onto(tcx, impl_def_id, impl_trait_ref.args);
50 let bound_trait_m_sig =
51 tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_to_impl_m_args).skip_norm_wip();
52 let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, bound_trait_m_sig);
53 let trait_m_sig_with_self_for_diag = tcx.liberate_late_bound_regions(
55 impl_m.def_id,
56 tcx.fn_sig(trait_m.def_id)
57 .instantiate(
58 tcx,
59 tcx.mk_args_from_iter(
60 [tcx.types.self_param.into()]
61 .into_iter()
62 .chain(trait_m_to_impl_m_args.iter().skip(1)),
63 ),
64 )
65 .skip_norm_wip(),
66 );
67
68 let Ok(hidden_tys) = tcx.collect_return_position_impl_trait_in_trait_tys(impl_m.def_id) else {
69 return;
71 };
72
73 if hidden_tys.items().any(|(_, &ty)| ty.skip_binder().references_error()) {
74 return;
75 }
76
77 let mut collector = ImplTraitInTraitCollector { tcx, depth: 0, types: FxIndexSet::default() };
78 if trait_m_sig.visit_with(&mut collector).is_break() {
79 return;
80 }
81
82 let mut trait_bounds = ::alloc::vec::Vec::new()vec![];
84 let mut impl_bounds = ::alloc::vec::Vec::new()vec![];
86 let mut pairs = ::alloc::vec::Vec::new()vec![];
88
89 for trait_projection in collector.types.into_iter().rev() {
90 let impl_opaque_args = trait_projection.args.rebase_onto(tcx, trait_m.def_id, impl_m_args);
91 let hidden_ty =
92 hidden_tys[&trait_projection.kind].instantiate(tcx, impl_opaque_args).skip_norm_wip();
93
94 let impl_opaque = if let ty::Alias(_, alias) = *hidden_ty.kind()
96 && let Some(impl_opaque) = alias.try_to_opaque()
97 {
98 impl_opaque
99 } else {
100 report_mismatched_rpitit_signature(
101 tcx,
102 trait_m_sig_with_self_for_diag,
103 trait_m_sig,
104 trait_m.def_id,
105 impl_m.def_id,
106 None,
107 is_internal,
108 );
109 return;
110 };
111
112 if !tcx.hir_get_if_local(impl_opaque.kind).is_some_and(|node| {
115 #[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!(
116 node.expect_opaque_ty().origin,
117 hir::OpaqueTyOrigin::AsyncFn { parent, .. } | hir::OpaqueTyOrigin::FnReturn { parent, .. }
118 if parent == impl_m.def_id.expect_local()
119 )
120 }) {
121 report_mismatched_rpitit_signature(
122 tcx,
123 trait_m_sig_with_self_for_diag,
124 trait_m_sig,
125 trait_m.def_id,
126 impl_m.def_id,
127 None,
128 is_internal,
129 );
130 return;
131 }
132
133 trait_bounds.extend(
134 tcx.item_bounds(trait_projection.kind)
135 .iter_instantiated(tcx, trait_projection.args)
136 .map(Unnormalized::skip_norm_wip),
137 );
138 impl_bounds.extend(elaborate(
139 tcx,
140 tcx.explicit_item_bounds(impl_opaque.kind)
141 .iter_instantiated_copied(tcx, impl_opaque.args)
142 .map(Unnormalized::skip_norm_wip),
143 ));
144
145 pairs.push((trait_projection, impl_opaque));
146 }
147
148 let hybrid_clauses = tcx
149 .clauses_of(impl_def_id)
150 .instantiate_identity(tcx)
151 .into_iter()
152 .chain(tcx.clauses_of(trait_m.def_id).instantiate_own(tcx, trait_m_to_impl_m_args))
153 .map(|(clause, _)| clause.skip_norm_wip());
154 let param_env =
155 normalize_param_env_or_error(tcx, hybrid_clauses.collect(), ObligationCause::dummy());
156
157 let ref infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
158 let ocx = ObligationCtxt::new(infcx);
159
160 let Ok((trait_bounds, impl_bounds)) = ocx.deeply_normalize(
169 &ObligationCause::dummy(),
170 param_env,
171 Unnormalized::new_wip((trait_bounds, impl_bounds)),
172 ) else {
173 tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (selection)");
174 return;
175 };
176
177 let mut implied_wf_types = FxIndexSet::default();
182 implied_wf_types.extend(trait_m_sig.inputs_and_output);
183 implied_wf_types.extend(ocx.normalize(
184 &ObligationCause::dummy(),
185 param_env,
186 Unnormalized::new_wip(trait_m_sig.inputs_and_output),
187 ));
188 if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
189 tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (selection)");
190 return;
191 }
192 let errors = infcx.resolve_regions(impl_m.def_id.expect_local(), param_env, implied_wf_types);
193 if !errors.is_empty() {
194 tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (regions)");
195 return;
196 }
197 let Ok((trait_bounds, impl_bounds)) =
199 infcx.deeply_resolve_via_region_graph((trait_bounds, impl_bounds))
200 else {
201 tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (resolution)");
204 return;
205 };
206
207 if trait_bounds.references_error() || impl_bounds.references_error() {
208 return;
209 }
210
211 let trait_bounds = FxIndexSet::from_iter(trait_bounds.fold_with(&mut FullyAnonymize { tcx }));
217 let impl_bounds = impl_bounds.fold_with(&mut FullyAnonymize { tcx });
218
219 for (clause, span) in impl_bounds {
225 if !trait_bounds.contains(&clause) {
226 report_mismatched_rpitit_signature(
227 tcx,
228 trait_m_sig_with_self_for_diag,
229 trait_m_sig,
230 trait_m.def_id,
231 impl_m.def_id,
232 Some(span),
233 is_internal,
234 );
235 return;
236 }
237 }
238
239 for (trait_projection, impl_opaque) in pairs {
244 let impl_variances = tcx.variances_of(impl_opaque.kind);
245 let impl_captures: FxIndexSet<_> = impl_opaque
246 .args
247 .iter()
248 .zip_eq(impl_variances)
249 .filter(|(_, v)| **v == ty::Invariant)
250 .map(|(arg, _)| arg)
251 .collect();
252
253 let trait_variances = tcx.variances_of(trait_projection.kind);
254 let mut trait_captures = FxIndexSet::default();
255 for (arg, variance) in trait_projection.args.iter().zip_eq(trait_variances) {
256 if *variance != ty::Invariant {
257 continue;
258 }
259 arg.visit_with(&mut CollectParams { params: &mut trait_captures });
260 }
261
262 if !trait_captures.iter().all(|arg| impl_captures.contains(arg)) {
263 report_mismatched_rpitit_captures(
264 tcx,
265 impl_opaque.kind.expect_local(),
266 trait_captures,
267 is_internal,
268 );
269 }
270 }
271}
272
273struct ImplTraitInTraitCollector<'tcx> {
274 tcx: TyCtxt<'tcx>,
275 depth: usize,
276 types: FxIndexSet<ty::ProjectionAliasTy<'tcx>>,
277}
278
279impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'tcx> {
282 type Result = ControlFlow<()>;
283
284 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
285 if let ty::Alias(_, alias) = *ty.kind()
286 && let Some(proj) = alias.try_to_projection()
287 && self.tcx.is_impl_trait_in_trait(proj.kind)
288 {
289 if !self.tcx.recursion_limit().value_within_limit(self.depth) {
290 let mut err = self.tcx.dcx().struct_span_err(
291 self.tcx.def_span(proj.kind),
292 "recursion limit exceeded while collecting implied RPITIT bounds",
293 );
294 suggest_new_overflow_limit(self.tcx, &mut err);
295 err.emit();
296 return ControlFlow::Break(());
297 }
298 if self.types.insert(proj) {
299 self.depth += 1;
300 for (pred, _) in self
301 .tcx
302 .explicit_item_bounds(proj.kind)
303 .iter_instantiated_copied(self.tcx, proj.args)
304 .map(Unnormalized::skip_norm_wip)
305 {
306 pred.visit_with(self)?;
307 }
308 self.depth -= 1;
309 }
310 } else {
311 ty.super_visit_with(self)?;
312 }
313 ControlFlow::Continue(())
314 }
315}
316
317fn report_mismatched_rpitit_signature<'tcx>(
318 tcx: TyCtxt<'tcx>,
319 trait_m_sig: ty::FnSig<'tcx>,
320 trait_m_sig_with_impl_self: ty::FnSig<'tcx>,
321 trait_m_def_id: DefId,
322 impl_m_def_id: DefId,
323 unmatched_bound: Option<Span>,
324 is_internal: bool,
325) {
326 let mapping = std::iter::zip(
327 tcx.fn_sig(trait_m_def_id).skip_binder().bound_vars(),
328 tcx.fn_sig(impl_m_def_id).skip_binder().bound_vars(),
329 )
330 .enumerate()
331 .filter_map(|(idx, (impl_bv, trait_bv))| {
332 if let ty::BoundVariableKind::Region(impl_bv) = impl_bv
333 && let ty::BoundVariableKind::Region(trait_bv) = trait_bv
334 {
335 let var = ty::BoundVar::from_usize(idx);
336 Some((
337 ty::LateParamRegionKind::from_bound(var, impl_bv),
338 ty::LateParamRegionKind::from_bound(var, trait_bv),
339 ))
340 } else {
341 None
342 }
343 })
344 .collect();
345
346 let mut return_ty = trait_m_sig.output().fold_with(&mut super::RemapLateParam { tcx, mapping });
347
348 let mut maybe_use_bounds_for_impl = None;
351
352 if tcx.asyncness(impl_m_def_id).is_async() && tcx.asyncness(trait_m_def_id).is_async() {
353 let &ty::Alias(
354 _,
355 ty::AliasTy { kind: ty::Projection { def_id: future_ty_def_id }, args, .. },
356 ) = return_ty.kind()
357 else {
358 ::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!(
359 tcx.def_span(trait_m_def_id),
360 "expected return type of async fn in trait to be a AFIT projection"
361 );
362 };
363 let Some(future_output_ty) = tcx
364 .explicit_item_bounds(future_ty_def_id)
365 .iter_instantiated_copied(tcx, args)
366 .map(Unnormalized::skip_norm_wip)
367 .find_map(|(clause, _)| match clause.kind().no_bound_vars()? {
368 ty::ClauseKind::Projection(proj) => proj.term.as_type(),
369 _ => None,
370 })
371 else {
372 ::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");
373 };
374 return_ty = future_output_ty;
375 } else {
376 maybe_use_bounds_for_impl =
377 rpitit_use_bounds_for_impl(tcx, trait_m_def_id, trait_m_sig_with_impl_self.output());
378 }
379
380 let (span, impl_return_span, pre, post) =
381 match tcx.hir_node_by_def_id(impl_m_def_id.expect_local()).fn_decl().unwrap().output {
382 hir::FnRetTy::DefaultReturn(span) => (tcx.def_span(impl_m_def_id), span, "-> ", " "),
383 hir::FnRetTy::Return(ty) => (ty.span, ty.span, "", ""),
384 };
385 let trait_return_span =
386 tcx.hir_get_if_local(trait_m_def_id).map(|node| match node.fn_decl().unwrap().output {
387 hir::FnRetTy::DefaultReturn(_) => tcx.def_span(trait_m_def_id),
388 hir::FnRetTy::Return(ty) => ty.span,
389 });
390
391 let return_ty_suggestion =
400 {
let _guard = NoTrimmedGuard::new();
{
let _guard =
::rustc_middle::ty::print::pretty::RtnModeHelper::with(RtnMode::ForSignature);
match &maybe_use_bounds_for_impl {
Some(use_bound) =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} + {1}", return_ty,
use_bound))
}),
None =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", return_ty))
}),
}
}
}with_no_trimmed_paths!(with_types_for_signature!(match &maybe_use_bounds_for_impl {
401 Some(use_bound) => format!("{return_ty} + {use_bound}"),
402 None => format!("{return_ty}"),
403 }));
404
405 let span = unmatched_bound.unwrap_or(span);
406 tcx.emit_node_span_lint(
407 if is_internal { REFINING_IMPL_TRAIT_INTERNAL } else { REFINING_IMPL_TRAIT_REACHABLE },
408 tcx.local_def_id_to_hir_id(impl_m_def_id.expect_local()),
409 span,
410 crate::diagnostics::ReturnPositionImplTraitInTraitRefined {
411 impl_return_span,
412 trait_return_span,
413 pre,
414 post,
415 return_ty: return_ty_suggestion,
416 unmatched_bound,
417 },
418 );
419}
420
421fn type_visibility<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<ty::Visibility<ModId>> {
422 match *ty.kind() {
423 ty::Ref(_, ty, _) => type_visibility(tcx, ty),
424 ty::Adt(def, args) => {
425 if def.is_fundamental() {
426 type_visibility(tcx, args.type_at(0))
427 } else {
428 Some(tcx.visibility(def.did()))
429 }
430 }
431 _ => None,
432 }
433}
434
435struct FullyAnonymize<'tcx> {
438 tcx: TyCtxt<'tcx>,
439}
440
441impl<'tcx> TypeFolder<TyCtxt<'tcx>> for FullyAnonymize<'tcx> {
442 fn cx(&self) -> TyCtxt<'tcx> {
443 self.tcx
444 }
445
446 fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
447 where
448 T: TypeFoldable<TyCtxt<'tcx>>,
449 {
450 let bound_vars = self.tcx.mk_bound_variable_kinds_from_iter(t.bound_vars().iter().map(
451 |kind| match kind {
452 ty::BoundVariableKind::Ty(_) => ty::BoundVariableKind::Ty(ty::BoundTyKind::Anon),
453 ty::BoundVariableKind::Region(_) => {
454 ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon)
455 }
456 ty::BoundVariableKind::Const => ty::BoundVariableKind::Const,
457 },
458 ));
459 ty::Binder::bind_with_vars(t.skip_binder().fold_with(self), bound_vars)
460 }
461
462 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
463 if let ty::RegionKind::ReBound(ty::BoundVarIndexKind::Bound(debruijn), bound_re) = r.kind()
464 {
465 ty::Region::new_anon_bound(self.tcx, debruijn, bound_re.var)
466 } else {
467 r
468 }
469 }
470
471 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
472 if !t.has_bound_vars() {
473 return t;
474 }
475 if let ty::Bound(ty::BoundVarIndexKind::Bound(debruijn), bound_ty) = *t.kind() {
476 let bound_ty = ty::BoundTy { var: bound_ty.var, kind: ty::BoundTyKind::Anon };
477 Ty::new_bound(self.tcx, debruijn, bound_ty)
478 } else {
479 t.super_fold_with(self)
480 }
481 }
482
483 fn fold_const(&mut self, c: ty::Const<'tcx>) -> ty::Const<'tcx> {
484 if !c.has_bound_vars() {
485 return c;
486 }
487 if let ty::ConstKind::Bound(ty::BoundVarIndexKind::Bound(debruijn), bound_ct) = c.kind() {
488 ty::Const::new_anon_bound(self.tcx, debruijn, bound_ct.var)
489 } else {
490 c.super_fold_with(self)
491 }
492 }
493}
494
495struct CollectParams<'a, 'tcx> {
496 params: &'a mut FxIndexSet<ty::GenericArg<'tcx>>,
497}
498impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for CollectParams<'_, 'tcx> {
499 fn visit_ty(&mut self, ty: Ty<'tcx>) {
500 if let ty::Param(_) = ty.kind() {
501 self.params.insert(ty.into());
502 } else {
503 ty.super_visit_with(self);
504 }
505 }
506 fn visit_region(&mut self, r: ty::Region<'tcx>) {
507 match r.kind() {
508 ty::ReEarlyParam(_) | ty::ReLateParam(_) => {
509 self.params.insert(r.into());
510 }
511 _ => {}
512 }
513 }
514 fn visit_const(&mut self, ct: ty::Const<'tcx>) {
515 if let ty::ConstKind::Param(_) = ct.kind() {
516 self.params.insert(ct.into());
517 } else {
518 ct.super_visit_with(self);
519 }
520 }
521}
522
523fn rpitit_use_bounds_for_impl<'tcx>(
530 tcx: TyCtxt<'tcx>,
531 trait_m_def_id: DefId,
532 trait_return_ty: Ty<'tcx>,
533) -> Option<String> {
534 let ty::Alias(_, alias) = *trait_return_ty.kind() else {
535 return None;
536 };
537 let projection = alias.try_to_projection()?;
538 if !tcx.is_impl_trait_in_trait(projection.kind) {
539 return None;
540 }
541
542 let captured_lifetimes = tcx
545 .generics_of(projection.kind)
546 .own_params
547 .iter()
548 .filter(|param| #[allow(non_exhaustive_omitted_patterns)] match param.kind {
ty::GenericParamDefKind::Lifetime => true,
_ => false,
}matches!(param.kind, ty::GenericParamDefKind::Lifetime))
549 .count();
550 let late_bound_lifetimes = tcx
551 .fn_sig(trait_m_def_id)
552 .skip_binder()
553 .bound_vars()
554 .iter()
555 .filter(|var| #[allow(non_exhaustive_omitted_patterns)] match var {
ty::BoundVariableKind::Region(_) => true,
_ => false,
}matches!(var, ty::BoundVariableKind::Region(_)))
556 .count();
557 if captured_lifetimes == late_bound_lifetimes {
558 return None;
559 }
560
561 let mut captures = FxIndexSet::default();
562 for arg in projection.args {
563 arg.visit_with(&mut CollectParams { params: &mut captures });
564 }
565 captures.sort_by_cached_key(|arg| !#[allow(non_exhaustive_omitted_patterns)] match arg.kind() {
ty::GenericArgKind::Lifetime(_) => true,
_ => false,
}matches!(arg.kind(), ty::GenericArgKind::Lifetime(_)));
566 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use<{0}>",
captures.iter().join(", ")))
})format!("use<{}>", captures.iter().join(", ")))
567}
568
569fn report_mismatched_rpitit_captures<'tcx>(
570 tcx: TyCtxt<'tcx>,
571 impl_opaque_def_id: LocalDefId,
572 mut trait_captured_args: FxIndexSet<ty::GenericArg<'tcx>>,
573 is_internal: bool,
574) {
575 let Some(use_bound_span) =
576 tcx.hir_node_by_def_id(impl_opaque_def_id).expect_opaque_ty().bounds.iter().find_map(
577 |bound| match *bound {
578 rustc_hir::GenericBound::Use(_, span) => Some(span),
579 hir::GenericBound::Trait(_) | hir::GenericBound::Outlives(_) => None,
580 },
581 )
582 else {
583 tcx.dcx().delayed_bug("expected use<..> to undercapture in an impl opaque");
585 return;
586 };
587
588 trait_captured_args
589 .sort_by_cached_key(|arg| !#[allow(non_exhaustive_omitted_patterns)] match arg.kind() {
ty::GenericArgKind::Lifetime(_) => true,
_ => false,
}matches!(arg.kind(), ty::GenericArgKind::Lifetime(_)));
590 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(", "));
591
592 tcx.emit_node_span_lint(
593 if is_internal { REFINING_IMPL_TRAIT_INTERNAL } else { REFINING_IMPL_TRAIT_REACHABLE },
594 tcx.local_def_id_to_hir_id(impl_opaque_def_id),
595 use_bound_span,
596 crate::diagnostics::ReturnPositionImplTraitInTraitRefinedLifetimes {
597 suggestion_span: use_bound_span,
598 suggestion,
599 },
600 );
601}