rustc_hir_analysis/check/compare_impl_item/
refine.rs1use 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::traits::ObligationCause;
8use rustc_middle::ty::print::{with_no_trimmed_paths, with_types_for_signature};
9use rustc_middle::ty::{
10 self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperVisitable, TypeVisitable,
11 TypeVisitableExt, TypeVisitor, TypingMode, Unnormalized,
12};
13use rustc_span::def_id::ModId;
14use rustc_span::{Span, span_bug};
15use rustc_trait_selection::regions::InferCtxtRegionExt;
16use rustc_trait_selection::traits::{ObligationCtxt, elaborate, normalize_param_env_or_error};
17
18pub(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 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 || 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 =
48 tcx.fn_sig(trait_m.def_id).instantiate(tcx, trait_m_to_impl_m_args).skip_norm_wip();
49 let trait_m_sig = tcx.liberate_late_bound_regions(impl_m.def_id, bound_trait_m_sig);
50 let trait_m_sig_with_self_for_diag = tcx.liberate_late_bound_regions(
52 impl_m.def_id,
53 tcx.fn_sig(trait_m.def_id)
54 .instantiate(
55 tcx,
56 tcx.mk_args_from_iter(
57 [tcx.types.self_param.into()]
58 .into_iter()
59 .chain(trait_m_to_impl_m_args.iter().skip(1)),
60 ),
61 )
62 .skip_norm_wip(),
63 );
64
65 let Ok(hidden_tys) = tcx.collect_return_position_impl_trait_in_trait_tys(impl_m.def_id) else {
66 return;
68 };
69
70 if hidden_tys.items().any(|(_, &ty)| ty.skip_binder().references_error()) {
71 return;
72 }
73
74 let mut collector = ImplTraitInTraitCollector { tcx, types: FxIndexSet::default() };
75 trait_m_sig.visit_with(&mut collector);
76
77 let mut trait_bounds = ::alloc::vec::Vec::new()vec![];
79 let mut impl_bounds = ::alloc::vec::Vec::new()vec![];
81 let mut pairs = ::alloc::vec::Vec::new()vec![];
83
84 for trait_projection in collector.types.into_iter().rev() {
85 let impl_opaque_args = trait_projection.args.rebase_onto(tcx, trait_m.def_id, impl_m_args);
86 let hidden_ty =
87 hidden_tys[&trait_projection.kind].instantiate(tcx, impl_opaque_args).skip_norm_wip();
88
89 let impl_opaque = if let ty::Alias(_, alias) = *hidden_ty.kind()
91 && let Some(impl_opaque) = alias.try_to_opaque()
92 {
93 impl_opaque
94 } else {
95 report_mismatched_rpitit_signature(
96 tcx,
97 trait_m_sig_with_self_for_diag,
98 trait_m.def_id,
99 impl_m.def_id,
100 None,
101 is_internal,
102 );
103 return;
104 };
105
106 if !tcx.hir_get_if_local(impl_opaque.kind).is_some_and(|node| {
109 #[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!(
110 node.expect_opaque_ty().origin,
111 hir::OpaqueTyOrigin::AsyncFn { parent, .. } | hir::OpaqueTyOrigin::FnReturn { parent, .. }
112 if parent == impl_m.def_id.expect_local()
113 )
114 }) {
115 report_mismatched_rpitit_signature(
116 tcx,
117 trait_m_sig_with_self_for_diag,
118 trait_m.def_id,
119 impl_m.def_id,
120 None,
121 is_internal,
122 );
123 return;
124 }
125
126 trait_bounds.extend(
127 tcx.item_bounds(trait_projection.kind)
128 .iter_instantiated(tcx, trait_projection.args)
129 .map(Unnormalized::skip_norm_wip),
130 );
131 impl_bounds.extend(elaborate(
132 tcx,
133 tcx.explicit_item_bounds(impl_opaque.kind)
134 .iter_instantiated_copied(tcx, impl_opaque.args)
135 .map(Unnormalized::skip_norm_wip),
136 ));
137
138 pairs.push((trait_projection, impl_opaque));
139 }
140
141 let hybrid_clauses = tcx
142 .clauses_of(impl_def_id)
143 .instantiate_identity(tcx)
144 .into_iter()
145 .chain(tcx.clauses_of(trait_m.def_id).instantiate_own(tcx, trait_m_to_impl_m_args))
146 .map(|(clause, _)| clause.skip_norm_wip());
147 let param_env = ty::ParamEnv::new(tcx, hybrid_clauses);
148 let param_env = normalize_param_env_or_error(tcx, param_env, ObligationCause::dummy());
149
150 let ref infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
151 let ocx = ObligationCtxt::new(infcx);
152
153 let Ok((trait_bounds, impl_bounds)) = ocx.deeply_normalize(
162 &ObligationCause::dummy(),
163 param_env,
164 Unnormalized::new_wip((trait_bounds, impl_bounds)),
165 ) else {
166 tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (selection)");
167 return;
168 };
169
170 let mut implied_wf_types = FxIndexSet::default();
175 implied_wf_types.extend(trait_m_sig.inputs_and_output);
176 implied_wf_types.extend(ocx.normalize(
177 &ObligationCause::dummy(),
178 param_env,
179 Unnormalized::new_wip(trait_m_sig.inputs_and_output),
180 ));
181 if !ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
182 tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (selection)");
183 return;
184 }
185 let errors = infcx.resolve_regions(impl_m.def_id.expect_local(), param_env, implied_wf_types);
186 if !errors.is_empty() {
187 tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (regions)");
188 return;
189 }
190 let Ok((trait_bounds, impl_bounds)) =
192 infcx.deeply_resolve_via_region_graph((trait_bounds, impl_bounds))
193 else {
194 tcx.dcx().delayed_bug("encountered errors when checking RPITIT refinement (resolution)");
197 return;
198 };
199
200 if trait_bounds.references_error() || impl_bounds.references_error() {
201 return;
202 }
203
204 let trait_bounds = FxIndexSet::from_iter(trait_bounds.fold_with(&mut Anonymize { tcx }));
210 let impl_bounds = impl_bounds.fold_with(&mut Anonymize { tcx });
211
212 for (clause, span) in impl_bounds {
218 if !trait_bounds.contains(&clause) {
219 report_mismatched_rpitit_signature(
220 tcx,
221 trait_m_sig_with_self_for_diag,
222 trait_m.def_id,
223 impl_m.def_id,
224 Some(span),
225 is_internal,
226 );
227 return;
228 }
229 }
230
231 for (trait_projection, impl_opaque) in pairs {
236 let impl_variances = tcx.variances_of(impl_opaque.kind);
237 let impl_captures: FxIndexSet<_> = impl_opaque
238 .args
239 .iter()
240 .zip_eq(impl_variances)
241 .filter(|(_, v)| **v == ty::Invariant)
242 .map(|(arg, _)| arg)
243 .collect();
244
245 let trait_variances = tcx.variances_of(trait_projection.kind);
246 let mut trait_captures = FxIndexSet::default();
247 for (arg, variance) in trait_projection.args.iter().zip_eq(trait_variances) {
248 if *variance != ty::Invariant {
249 continue;
250 }
251 arg.visit_with(&mut CollectParams { params: &mut trait_captures });
252 }
253
254 if !trait_captures.iter().all(|arg| impl_captures.contains(arg)) {
255 report_mismatched_rpitit_captures(
256 tcx,
257 impl_opaque.kind.expect_local(),
258 trait_captures,
259 is_internal,
260 );
261 }
262 }
263}
264
265struct ImplTraitInTraitCollector<'tcx> {
266 tcx: TyCtxt<'tcx>,
267 types: FxIndexSet<ty::ProjectionAliasTy<'tcx>>,
268}
269
270impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for ImplTraitInTraitCollector<'tcx> {
271 fn visit_ty(&mut self, ty: Ty<'tcx>) {
272 if let ty::Alias(_, alias) = *ty.kind()
273 && let Some(proj) = alias.try_to_projection()
274 && self.tcx.is_impl_trait_in_trait(proj.kind)
275 {
276 if self.types.insert(proj) {
277 for (pred, _) in self
278 .tcx
279 .explicit_item_bounds(proj.kind)
280 .iter_instantiated_copied(self.tcx, proj.args)
281 .map(Unnormalized::skip_norm_wip)
282 {
283 pred.visit_with(self);
284 }
285 }
286 } else {
287 ty.super_visit_with(self);
288 }
289 }
290}
291
292fn report_mismatched_rpitit_signature<'tcx>(
293 tcx: TyCtxt<'tcx>,
294 trait_m_sig: ty::FnSig<'tcx>,
295 trait_m_def_id: DefId,
296 impl_m_def_id: DefId,
297 unmatched_bound: Option<Span>,
298 is_internal: bool,
299) {
300 let mapping = std::iter::zip(
301 tcx.fn_sig(trait_m_def_id).skip_binder().bound_vars(),
302 tcx.fn_sig(impl_m_def_id).skip_binder().bound_vars(),
303 )
304 .enumerate()
305 .filter_map(|(idx, (impl_bv, trait_bv))| {
306 if let ty::BoundVariableKind::Region(impl_bv) = impl_bv
307 && let ty::BoundVariableKind::Region(trait_bv) = trait_bv
308 {
309 let var = ty::BoundVar::from_usize(idx);
310 Some((
311 ty::LateParamRegionKind::from_bound(var, impl_bv),
312 ty::LateParamRegionKind::from_bound(var, trait_bv),
313 ))
314 } else {
315 None
316 }
317 })
318 .collect();
319
320 let mut return_ty = trait_m_sig.output().fold_with(&mut super::RemapLateParam { tcx, mapping });
321
322 if tcx.asyncness(impl_m_def_id).is_async() && tcx.asyncness(trait_m_def_id).is_async() {
323 let &ty::Alias(
324 _,
325 ty::AliasTy { kind: ty::Projection { def_id: future_ty_def_id }, args, .. },
326 ) = return_ty.kind()
327 else {
328 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!(
329 tcx.def_span(trait_m_def_id),
330 "expected return type of async fn in trait to be a AFIT projection"
331 );
332 };
333 let Some(future_output_ty) = tcx
334 .explicit_item_bounds(future_ty_def_id)
335 .iter_instantiated_copied(tcx, args)
336 .map(Unnormalized::skip_norm_wip)
337 .find_map(|(clause, _)| match clause.kind().no_bound_vars()? {
338 ty::ClauseKind::Projection(proj) => proj.term.as_type(),
339 _ => None,
340 })
341 else {
342 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");
343 };
344 return_ty = future_output_ty;
345 }
346
347 let (span, impl_return_span, pre, post) =
348 match tcx.hir_node_by_def_id(impl_m_def_id.expect_local()).fn_decl().unwrap().output {
349 hir::FnRetTy::DefaultReturn(span) => (tcx.def_span(impl_m_def_id), span, "-> ", " "),
350 hir::FnRetTy::Return(ty) => (ty.span, ty.span, "", ""),
351 };
352 let trait_return_span =
353 tcx.hir_get_if_local(trait_m_def_id).map(|node| match node.fn_decl().unwrap().output {
354 hir::FnRetTy::DefaultReturn(_) => tcx.def_span(trait_m_def_id),
355 hir::FnRetTy::Return(ty) => ty.span,
356 });
357
358 let return_ty_suggestion =
367 {
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}")));
368
369 let span = unmatched_bound.unwrap_or(span);
370 tcx.emit_node_span_lint(
371 if is_internal { REFINING_IMPL_TRAIT_INTERNAL } else { REFINING_IMPL_TRAIT_REACHABLE },
372 tcx.local_def_id_to_hir_id(impl_m_def_id.expect_local()),
373 span,
374 crate::diagnostics::ReturnPositionImplTraitInTraitRefined {
375 impl_return_span,
376 trait_return_span,
377 pre,
378 post,
379 return_ty: return_ty_suggestion,
380 unmatched_bound,
381 },
382 );
383}
384
385fn type_visibility<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<ty::Visibility<ModId>> {
386 match *ty.kind() {
387 ty::Ref(_, ty, _) => type_visibility(tcx, ty),
388 ty::Adt(def, args) => {
389 if def.is_fundamental() {
390 type_visibility(tcx, args.type_at(0))
391 } else {
392 Some(tcx.visibility(def.did()))
393 }
394 }
395 _ => None,
396 }
397}
398
399struct Anonymize<'tcx> {
400 tcx: TyCtxt<'tcx>,
401}
402
403impl<'tcx> TypeFolder<TyCtxt<'tcx>> for Anonymize<'tcx> {
404 fn cx(&self) -> TyCtxt<'tcx> {
405 self.tcx
406 }
407
408 fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
409 where
410 T: TypeFoldable<TyCtxt<'tcx>>,
411 {
412 self.tcx.anonymize_bound_vars(t)
413 }
414}
415
416struct CollectParams<'a, 'tcx> {
417 params: &'a mut FxIndexSet<ty::GenericArg<'tcx>>,
418}
419impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for CollectParams<'_, 'tcx> {
420 fn visit_ty(&mut self, ty: Ty<'tcx>) {
421 if let ty::Param(_) = ty.kind() {
422 self.params.insert(ty.into());
423 } else {
424 ty.super_visit_with(self);
425 }
426 }
427 fn visit_region(&mut self, r: ty::Region<'tcx>) {
428 match r.kind() {
429 ty::ReEarlyParam(_) | ty::ReLateParam(_) => {
430 self.params.insert(r.into());
431 }
432 _ => {}
433 }
434 }
435 fn visit_const(&mut self, ct: ty::Const<'tcx>) {
436 if let ty::ConstKind::Param(_) = ct.kind() {
437 self.params.insert(ct.into());
438 } else {
439 ct.super_visit_with(self);
440 }
441 }
442}
443
444fn report_mismatched_rpitit_captures<'tcx>(
445 tcx: TyCtxt<'tcx>,
446 impl_opaque_def_id: LocalDefId,
447 mut trait_captured_args: FxIndexSet<ty::GenericArg<'tcx>>,
448 is_internal: bool,
449) {
450 let Some(use_bound_span) =
451 tcx.hir_node_by_def_id(impl_opaque_def_id).expect_opaque_ty().bounds.iter().find_map(
452 |bound| match *bound {
453 rustc_hir::GenericBound::Use(_, span) => Some(span),
454 hir::GenericBound::Trait(_) | hir::GenericBound::Outlives(_) => None,
455 },
456 )
457 else {
458 tcx.dcx().delayed_bug("expected use<..> to undercapture in an impl opaque");
460 return;
461 };
462
463 trait_captured_args
464 .sort_by_cached_key(|arg| !#[allow(non_exhaustive_omitted_patterns)] match arg.kind() {
ty::GenericArgKind::Lifetime(_) => true,
_ => false,
}matches!(arg.kind(), ty::GenericArgKind::Lifetime(_)));
465 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(", "));
466
467 tcx.emit_node_span_lint(
468 if is_internal { REFINING_IMPL_TRAIT_INTERNAL } else { REFINING_IMPL_TRAIT_REACHABLE },
469 tcx.local_def_id_to_hir_id(impl_opaque_def_id),
470 use_bound_span,
471 crate::diagnostics::ReturnPositionImplTraitInTraitRefinedLifetimes {
472 suggestion_span: use_bound_span,
473 suggestion,
474 },
475 );
476}