rustc_hir_analysis/impl_wf_check/
min_specialization.rs1use rustc_data_structures::fx::FxHashSet;
69use rustc_hir::def_id::{DefId, LocalDefId};
70use rustc_infer::infer::TyCtxtInferExt;
71use rustc_infer::traits::ObligationCause;
72use rustc_infer::traits::specialization_graph::Node;
73use rustc_middle::ty::trait_def::TraitSpecializationKind;
74use rustc_middle::ty::{
75 self, GenericArg, GenericArgs, GenericArgsRef, TyCtxt, TypeVisitableExt, TypingMode,
76};
77use rustc_span::{ErrorGuaranteed, Span};
78use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
79use rustc_trait_selection::traits::{self, ObligationCtxt, translate_args_with_cause, wf};
80use tracing::{debug, instrument};
81
82use crate::errors::GenericArgsOnOverriddenImpl;
83use crate::{constrained_generic_params as cgp, errors};
84
85pub(super) fn check_min_specialization(
86 tcx: TyCtxt<'_>,
87 impl_def_id: LocalDefId,
88) -> Result<(), ErrorGuaranteed> {
89 if let Some(node) = parent_specialization_node(tcx, impl_def_id) {
90 check_always_applicable(tcx, impl_def_id, node)?;
91 }
92 Ok(())
93}
94
95fn parent_specialization_node(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId) -> Option<Node> {
96 let trait_ref = tcx.impl_trait_ref(impl1_def_id)?;
97 let trait_def = tcx.trait_def(trait_ref.skip_binder().def_id);
98
99 let impl2_node = trait_def.ancestors(tcx, impl1_def_id.to_def_id()).ok()?.nth(1)?;
100
101 let always_applicable_trait =
102 matches!(trait_def.specialization_kind, TraitSpecializationKind::AlwaysApplicable);
103 if impl2_node.is_from_trait() && !always_applicable_trait {
104 return None;
106 }
107 if trait_def.is_marker {
108 return None;
110 }
111 Some(impl2_node)
112}
113
114#[instrument(level = "debug", skip(tcx))]
116fn check_always_applicable(
117 tcx: TyCtxt<'_>,
118 impl1_def_id: LocalDefId,
119 impl2_node: Node,
120) -> Result<(), ErrorGuaranteed> {
121 let span = tcx.def_span(impl1_def_id);
122
123 let (impl1_args, impl2_args) = get_impl_args(tcx, impl1_def_id, impl2_node)?;
124 let impl2_def_id = impl2_node.def_id();
125 debug!(?impl2_def_id, ?impl2_args);
126
127 let parent_args = if impl2_node.is_from_trait() {
128 impl2_args.to_vec()
129 } else {
130 unconstrained_parent_impl_args(tcx, impl2_def_id, impl2_args)
131 };
132
133 check_has_items(tcx, impl1_def_id, impl2_node, span)
134 .and(check_static_lifetimes(tcx, &parent_args, span))
135 .and(check_duplicate_params(tcx, impl1_args, parent_args, span))
136 .and(check_predicates(tcx, impl1_def_id, impl1_args, impl2_node, impl2_args, span))
137}
138
139fn check_has_items(
140 tcx: TyCtxt<'_>,
141 impl1_def_id: LocalDefId,
142 impl2_node: Node,
143 span: Span,
144) -> Result<(), ErrorGuaranteed> {
145 if let Node::Impl(impl2_id) = impl2_node
146 && tcx.associated_item_def_ids(impl1_def_id).is_empty()
147 {
148 let base_impl_span = tcx.def_span(impl2_id);
149 return Err(tcx.dcx().emit_err(errors::EmptySpecialization { span, base_impl_span }));
150 }
151 Ok(())
152}
153
154fn get_impl_args(
167 tcx: TyCtxt<'_>,
168 impl1_def_id: LocalDefId,
169 impl2_node: Node,
170) -> Result<(GenericArgsRef<'_>, GenericArgsRef<'_>), ErrorGuaranteed> {
171 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
172 let ocx = ObligationCtxt::new_with_diagnostics(infcx);
173 let param_env = tcx.param_env(impl1_def_id);
174 let impl1_span = tcx.def_span(impl1_def_id);
175
176 let impl1_args = GenericArgs::identity_for_item(tcx, impl1_def_id);
177 let impl2_args = translate_args_with_cause(
178 infcx,
179 param_env,
180 impl1_def_id.to_def_id(),
181 impl1_args,
182 impl2_node,
183 &ObligationCause::misc(impl1_span, impl1_def_id),
184 );
185
186 let errors = ocx.select_all_or_error();
187 if !errors.is_empty() {
188 let guar = ocx.infcx.err_ctxt().report_fulfillment_errors(errors);
189 return Err(guar);
190 }
191
192 let assumed_wf_types = ocx.assumed_wf_types_and_report_errors(param_env, impl1_def_id)?;
193 let _ = ocx.resolve_regions_and_report_errors(impl1_def_id, param_env, assumed_wf_types);
194 let Ok(impl2_args) = infcx.fully_resolve(impl2_args) else {
195 let span = tcx.def_span(impl1_def_id);
196 let guar = tcx.dcx().emit_err(GenericArgsOnOverriddenImpl { span });
197 return Err(guar);
198 };
199 Ok((impl1_args, impl2_args))
200}
201
202fn unconstrained_parent_impl_args<'tcx>(
211 tcx: TyCtxt<'tcx>,
212 impl_def_id: DefId,
213 impl_args: GenericArgsRef<'tcx>,
214) -> Vec<GenericArg<'tcx>> {
215 let impl_generic_predicates = tcx.predicates_of(impl_def_id);
216 let mut unconstrained_parameters = FxHashSet::default();
217 let mut constrained_params = FxHashSet::default();
218 let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).map(ty::EarlyBinder::instantiate_identity);
219
220 for (clause, _) in impl_generic_predicates.predicates.iter() {
225 if let ty::ClauseKind::Projection(proj) = clause.kind().skip_binder() {
226 let unbound_trait_ref = proj.projection_term.trait_ref(tcx);
227 if Some(unbound_trait_ref) == impl_trait_ref {
228 continue;
229 }
230
231 unconstrained_parameters.extend(cgp::parameters_for(tcx, proj.projection_term, true));
232
233 for param in cgp::parameters_for(tcx, proj.term, false) {
234 if !unconstrained_parameters.contains(¶m) {
235 constrained_params.insert(param.0);
236 }
237 }
238
239 unconstrained_parameters.extend(cgp::parameters_for(tcx, proj.term, true));
240 }
241 }
242
243 impl_args
244 .iter()
245 .enumerate()
246 .filter(|&(idx, _)| !constrained_params.contains(&(idx as u32)))
247 .map(|(_, arg)| arg)
248 .collect()
249}
250
251fn check_duplicate_params<'tcx>(
272 tcx: TyCtxt<'tcx>,
273 impl1_args: GenericArgsRef<'tcx>,
274 parent_args: Vec<GenericArg<'tcx>>,
275 span: Span,
276) -> Result<(), ErrorGuaranteed> {
277 let mut base_params = cgp::parameters_for(tcx, parent_args, true);
278 base_params.sort_by_key(|param| param.0);
279 if let (_, [duplicate, ..]) = base_params.partition_dedup() {
280 let param = impl1_args[duplicate.0 as usize];
281 return Err(tcx
282 .dcx()
283 .struct_span_err(span, format!("specializing impl repeats parameter `{param}`"))
284 .emit());
285 }
286 Ok(())
287}
288
289fn check_static_lifetimes<'tcx>(
298 tcx: TyCtxt<'tcx>,
299 parent_args: &Vec<GenericArg<'tcx>>,
300 span: Span,
301) -> Result<(), ErrorGuaranteed> {
302 if tcx.any_free_region_meets(parent_args, |r| r.is_static()) {
303 return Err(tcx.dcx().emit_err(errors::StaticSpecialize { span }));
304 }
305 Ok(())
306}
307
308#[instrument(level = "debug", skip(tcx))]
319fn check_predicates<'tcx>(
320 tcx: TyCtxt<'tcx>,
321 impl1_def_id: LocalDefId,
322 impl1_args: GenericArgsRef<'tcx>,
323 impl2_node: Node,
324 impl2_args: GenericArgsRef<'tcx>,
325 span: Span,
326) -> Result<(), ErrorGuaranteed> {
327 let impl1_predicates: Vec<_> = traits::elaborate(
328 tcx,
329 tcx.predicates_of(impl1_def_id).instantiate(tcx, impl1_args).into_iter(),
330 )
331 .collect();
332
333 let mut impl2_predicates = if impl2_node.is_from_trait() {
334 Vec::new()
337 } else {
338 traits::elaborate(
339 tcx,
340 tcx.predicates_of(impl2_node.def_id())
341 .instantiate(tcx, impl2_args)
342 .into_iter()
343 .map(|(c, _s)| c.as_predicate()),
344 )
345 .collect()
346 };
347 debug!(?impl1_predicates, ?impl2_predicates);
348
349 let always_applicable_traits = impl1_predicates
365 .iter()
366 .copied()
367 .filter(|&(clause, _span)| {
368 matches!(
369 trait_specialization_kind(tcx, clause),
370 Some(TraitSpecializationKind::AlwaysApplicable)
371 )
372 })
373 .map(|(c, _span)| c.as_predicate());
374
375 for arg in tcx.impl_trait_ref(impl1_def_id).unwrap().instantiate_identity().args {
377 let Some(term) = arg.as_term() else {
378 continue;
379 };
380 let infcx = &tcx.infer_ctxt().build(TypingMode::non_body_analysis());
381 let obligations =
382 wf::obligations(infcx, tcx.param_env(impl1_def_id), impl1_def_id, 0, term, span)
383 .unwrap();
384
385 assert!(!obligations.has_infer());
386 impl2_predicates
387 .extend(traits::elaborate(tcx, obligations).map(|obligation| obligation.predicate))
388 }
389 impl2_predicates.extend(traits::elaborate(tcx, always_applicable_traits));
390
391 let mut res = Ok(());
392 for (clause, span) in impl1_predicates {
393 if !impl2_predicates.iter().any(|&pred2| clause.as_predicate() == pred2) {
394 res = res.and(check_specialization_on(tcx, clause, span))
395 }
396 }
397 res
398}
399
400#[instrument(level = "debug", skip(tcx))]
401fn check_specialization_on<'tcx>(
402 tcx: TyCtxt<'tcx>,
403 clause: ty::Clause<'tcx>,
404 span: Span,
405) -> Result<(), ErrorGuaranteed> {
406 match clause.kind().skip_binder() {
407 _ if clause.is_global() => Ok(()),
410 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => {
413 if matches!(
414 trait_specialization_kind(tcx, clause),
415 Some(TraitSpecializationKind::Marker)
416 ) {
417 Ok(())
418 } else {
419 Err(tcx
420 .dcx()
421 .struct_span_err(
422 span,
423 format!(
424 "cannot specialize on trait `{}`",
425 tcx.def_path_str(trait_ref.def_id),
426 ),
427 )
428 .emit())
429 }
430 }
431 ty::ClauseKind::Projection(ty::ProjectionPredicate { projection_term, term }) => Err(tcx
432 .dcx()
433 .struct_span_err(
434 span,
435 format!("cannot specialize on associated type `{projection_term} == {term}`",),
436 )
437 .emit()),
438 ty::ClauseKind::ConstArgHasType(..) => {
439 Ok(())
448 }
449 _ => Err(tcx
450 .dcx()
451 .struct_span_err(span, format!("cannot specialize on predicate `{clause}`"))
452 .emit()),
453 }
454}
455
456fn trait_specialization_kind<'tcx>(
457 tcx: TyCtxt<'tcx>,
458 clause: ty::Clause<'tcx>,
459) -> Option<TraitSpecializationKind> {
460 match clause.kind().skip_binder() {
461 ty::ClauseKind::Trait(ty::TraitPredicate { trait_ref, polarity: _ }) => {
462 Some(tcx.trait_def(trait_ref.def_id).specialization_kind)
463 }
464 ty::ClauseKind::RegionOutlives(_)
465 | ty::ClauseKind::TypeOutlives(_)
466 | ty::ClauseKind::Projection(_)
467 | ty::ClauseKind::ConstArgHasType(..)
468 | ty::ClauseKind::WellFormed(_)
469 | ty::ClauseKind::ConstEvaluatable(..)
470 | ty::ClauseKind::UnstableFeature(_)
471 | ty::ClauseKind::HostEffect(..) => None,
472 }
473}