]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs
New upstream version 1.71.1+dfsg1
[rustc.git] / compiler / rustc_hir_analysis / src / impl_wf_check / min_specialization.rs
CommitLineData
ba9703b0
XL
1//! # Minimal Specialization
2//!
3//! This module contains the checks for sound specialization used when the
4//! `min_specialization` feature is enabled. This requires that the impl is
5//! *always applicable*.
6//!
7//! If `impl1` specializes `impl2` then `impl1` is always applicable if we know
8//! that all the bounds of `impl2` are satisfied, and all of the bounds of
9//! `impl1` are satisfied for some choice of lifetimes then we know that
10//! `impl1` applies for any choice of lifetimes.
11//!
12//! ## Basic approach
13//!
14//! To enforce this requirement on specializations we take the following
15//! approach:
16//!
17//! 1. Match up the substs for `impl2` so that the implemented trait and
18//! self-type match those for `impl1`.
19//! 2. Check for any direct use of `'static` in the substs of `impl2`.
20//! 3. Check that all of the generic parameters of `impl1` occur at most once
21//! in the *unconstrained* substs for `impl2`. A parameter is constrained if
22//! its value is completely determined by an associated type projection
23//! predicate.
24//! 4. Check that all predicates on `impl1` either exist on `impl2` (after
25//! matching substs), or are well-formed predicates for the trait's type
26//! arguments.
27//!
28//! ## Example
29//!
30//! Suppose we have the following always applicable impl:
31//!
04454e1e 32//! ```ignore (illustrative)
ba9703b0
XL
33//! impl<T> SpecExtend<T> for std::vec::IntoIter<T> { /* specialized impl */ }
34//! impl<T, I: Iterator<Item=T>> SpecExtend<T> for I { /* default impl */ }
35//! ```
36//!
37//! We get that the subst for `impl2` are `[T, std::vec::IntoIter<T>]`. `T` is
38//! constrained to be `<I as Iterator>::Item`, so we check only
39//! `std::vec::IntoIter<T>` for repeated parameters, which it doesn't have. The
40//! predicates of `impl1` are only `T: Sized`, which is also a predicate of
41//! `impl2`. So this specialization is sound.
42//!
43//! ## Extensions
44//!
45//! Unfortunately not all specializations in the standard library are allowed
46//! by this. So there are two extensions to these rules that allow specializing
47//! on some traits: that is, using them as bounds on the specializing impl,
48//! even when they don't occur in the base impl.
49//!
50//! ### rustc_specialization_trait
51//!
52//! If a trait is always applicable, then it's sound to specialize on it. We
53//! check trait is always applicable in the same way as impls, except that step
54//! 4 is now "all predicates on `impl1` are always applicable". We require that
55//! `specialization` or `min_specialization` is enabled to implement these
56//! traits.
57//!
58//! ### rustc_unsafe_specialization_marker
59//!
60//! There are also some specialization on traits with no methods, including the
61//! stable `FusedIterator` trait. We allow marking marker traits with an
62//! unstable attribute that means we ignore them in point 3 of the checks
63//! above. This is unsound, in the sense that the specialized impl may be used
64//! when it doesn't apply, but we allow it in the short term since it can't
65//! cause use after frees with purely safe code in the same way as specializing
66//! on traits with methods can.
67
04454e1e 68use crate::errors::SubstsOnOverriddenImpl;
49aad941 69use crate::{constrained_generic_params as cgp, errors};
ba9703b0
XL
70
71use rustc_data_structures::fx::FxHashSet;
487cf647 72use rustc_hir as hir;
f9f354fc 73use rustc_hir::def_id::{DefId, LocalDefId};
ba9703b0 74use rustc_infer::infer::outlives::env::OutlivesEnvironment;
f2b60f7d 75use rustc_infer::infer::TyCtxtInferExt;
ba9703b0 76use rustc_infer::traits::specialization_graph::Node;
ba9703b0
XL
77use rustc_middle::ty::subst::{GenericArg, InternalSubsts, SubstsRef};
78use rustc_middle::ty::trait_def::TraitSpecializationKind;
9ffffee4 79use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
ba9703b0 80use rustc_span::Span;
2b03887a 81use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt;
f2b60f7d 82use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _;
49aad941 83use rustc_trait_selection::traits::{self, translate_substs_with_cause, wf, ObligationCtxt};
ba9703b0 84
064997fb 85pub(super) fn check_min_specialization(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) {
ba9703b0 86 if let Some(node) = parent_specialization_node(tcx, impl_def_id) {
f2b60f7d 87 check_always_applicable(tcx, impl_def_id, node);
ba9703b0
XL
88 }
89}
90
064997fb 91fn parent_specialization_node(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId) -> Option<Node> {
ba9703b0 92 let trait_ref = tcx.impl_trait_ref(impl1_def_id)?;
9c376795 93 let trait_def = tcx.trait_def(trait_ref.skip_binder().def_id);
ba9703b0 94
064997fb 95 let impl2_node = trait_def.ancestors(tcx, impl1_def_id.to_def_id()).ok()?.nth(1)?;
ba9703b0
XL
96
97 let always_applicable_trait =
98 matches!(trait_def.specialization_kind, TraitSpecializationKind::AlwaysApplicable);
99 if impl2_node.is_from_trait() && !always_applicable_trait {
100 // Implementing a normal trait isn't a specialization.
101 return None;
102 }
49aad941
FG
103 if trait_def.is_marker {
104 // Overlapping marker implementations are not really specializations.
105 return None;
106 }
ba9703b0
XL
107 Some(impl2_node)
108}
109
110/// Check that `impl1` is a sound specialization
487cf647 111#[instrument(level = "debug", skip(tcx))]
f2b60f7d 112fn check_always_applicable(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node) {
49aad941
FG
113 let span = tcx.def_span(impl1_def_id);
114 check_has_items(tcx, impl1_def_id, impl2_node, span);
115
f2b60f7d 116 if let Some((impl1_substs, impl2_substs)) = get_impl_substs(tcx, impl1_def_id, impl2_node) {
ba9703b0 117 let impl2_def_id = impl2_node.def_id();
487cf647 118 debug!(?impl2_def_id, ?impl2_substs);
ba9703b0 119
ba9703b0
XL
120 let parent_substs = if impl2_node.is_from_trait() {
121 impl2_substs.to_vec()
122 } else {
123 unconstrained_parent_impl_substs(tcx, impl2_def_id, impl2_substs)
124 };
125
487cf647 126 check_constness(tcx, impl1_def_id, impl2_node, span);
ba9703b0
XL
127 check_static_lifetimes(tcx, &parent_substs, span);
128 check_duplicate_params(tcx, impl1_substs, &parent_substs, span);
f2b60f7d 129 check_predicates(tcx, impl1_def_id, impl1_substs, impl2_node, impl2_substs, span);
ba9703b0
XL
130 }
131}
132
49aad941
FG
133fn check_has_items(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node, span: Span) {
134 if let Node::Impl(impl2_id) = impl2_node && tcx.associated_item_def_ids(impl1_def_id).is_empty() {
135 let base_impl_span = tcx.def_span(impl2_id);
136 tcx.sess.emit_err(errors::EmptySpecialization { span, base_impl_span });
137 }
138}
139
487cf647
FG
140/// Check that the specializing impl `impl1` is at least as const as the base
141/// impl `impl2`
142fn check_constness(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node, span: Span) {
143 if impl2_node.is_from_trait() {
144 // This isn't a specialization
145 return;
146 }
147
148 let impl1_constness = tcx.constness(impl1_def_id.to_def_id());
149 let impl2_constness = tcx.constness(impl2_node.def_id());
150
151 if let hir::Constness::Const = impl2_constness {
152 if let hir::Constness::NotConst = impl1_constness {
49aad941 153 tcx.sess.emit_err(errors::ConstSpecialize { span });
487cf647
FG
154 }
155 }
156}
157
ba9703b0
XL
158/// Given a specializing impl `impl1`, and the base impl `impl2`, returns two
159/// substitutions `(S1, S2)` that equate their trait references. The returned
160/// types are expressed in terms of the generics of `impl1`.
161///
162/// Example
163///
2b03887a 164/// ```ignore (illustrative)
ba9703b0
XL
165/// impl<A, B> Foo<A> for B { /* impl2 */ }
166/// impl<C> Foo<Vec<C>> for C { /* impl1 */ }
2b03887a 167/// ```
ba9703b0
XL
168///
169/// Would return `S1 = [C]` and `S2 = [Vec<C>, C]`.
9c376795
FG
170fn get_impl_substs(
171 tcx: TyCtxt<'_>,
064997fb 172 impl1_def_id: LocalDefId,
ba9703b0 173 impl2_node: Node,
9c376795 174) -> Option<(SubstsRef<'_>, SubstsRef<'_>)> {
2b03887a
FG
175 let infcx = &tcx.infer_ctxt().build();
176 let ocx = ObligationCtxt::new(infcx);
177 let param_env = tcx.param_env(impl1_def_id);
ba9703b0 178
2b03887a
FG
179 let assumed_wf_types =
180 ocx.assumed_wf_types(param_env, tcx.def_span(impl1_def_id), impl1_def_id);
ba9703b0 181
353b0b11 182 let impl1_substs = InternalSubsts::identity_for_item(tcx, impl1_def_id);
49aad941
FG
183 let impl1_span = tcx.def_span(impl1_def_id);
184 let impl2_substs = translate_substs_with_cause(
185 infcx,
186 param_env,
187 impl1_def_id.to_def_id(),
188 impl1_substs,
189 impl2_node,
190 |_, span| {
191 traits::ObligationCause::new(
192 impl1_span,
193 impl1_def_id,
194 traits::ObligationCauseCode::BindingObligation(impl2_node.def_id(), span),
195 )
196 },
197 );
f2b60f7d 198
2b03887a
FG
199 let errors = ocx.select_all_or_error();
200 if !errors.is_empty() {
353b0b11 201 ocx.infcx.err_ctxt().report_fulfillment_errors(&errors);
2b03887a
FG
202 return None;
203 }
f2b60f7d 204
9ffffee4 205 let implied_bounds = infcx.implied_bounds_tys(param_env, impl1_def_id, assumed_wf_types);
353b0b11
FG
206 let outlives_env = OutlivesEnvironment::with_bounds(param_env, implied_bounds);
207 let _ = ocx.resolve_regions_and_report_errors(impl1_def_id, &outlives_env);
2b03887a
FG
208 let Ok(impl2_substs) = infcx.fully_resolve(impl2_substs) else {
209 let span = tcx.def_span(impl1_def_id);
210 tcx.sess.emit_err(SubstsOnOverriddenImpl { span });
211 return None;
212 };
213 Some((impl1_substs, impl2_substs))
ba9703b0
XL
214}
215
216/// Returns a list of all of the unconstrained subst of the given impl.
217///
218/// For example given the impl:
219///
220/// impl<'a, T, I> ... where &'a I: IntoIterator<Item=&'a T>
221///
222/// This would return the substs corresponding to `['a, I]`, because knowing
223/// `'a` and `I` determines the value of `T`.
224fn unconstrained_parent_impl_substs<'tcx>(
225 tcx: TyCtxt<'tcx>,
226 impl_def_id: DefId,
227 impl_substs: SubstsRef<'tcx>,
228) -> Vec<GenericArg<'tcx>> {
229 let impl_generic_predicates = tcx.predicates_of(impl_def_id);
230 let mut unconstrained_parameters = FxHashSet::default();
231 let mut constrained_params = FxHashSet::default();
9c376795 232 let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).map(ty::EarlyBinder::subst_identity);
ba9703b0
XL
233
234 // Unfortunately the functions in `constrained_generic_parameters` don't do
235 // what we want here. We want only a list of constrained parameters while
236 // the functions in `cgp` add the constrained parameters to a list of
237 // unconstrained parameters.
238 for (predicate, _) in impl_generic_predicates.predicates.iter() {
487cf647
FG
239 if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) =
240 predicate.kind().skip_binder()
241 {
3dfed10e 242 let projection_ty = proj.projection_ty;
5099ac24 243 let projected_ty = proj.term;
ba9703b0
XL
244
245 let unbound_trait_ref = projection_ty.trait_ref(tcx);
246 if Some(unbound_trait_ref) == impl_trait_ref {
247 continue;
248 }
249
5099ac24 250 unconstrained_parameters.extend(cgp::parameters_for(&projection_ty, true));
ba9703b0 251
5099ac24 252 for param in cgp::parameters_for(&projected_ty, false) {
ba9703b0
XL
253 if !unconstrained_parameters.contains(&param) {
254 constrained_params.insert(param.0);
255 }
256 }
257
5099ac24 258 unconstrained_parameters.extend(cgp::parameters_for(&projected_ty, true));
ba9703b0
XL
259 }
260 }
261
262 impl_substs
263 .iter()
264 .enumerate()
265 .filter(|&(idx, _)| !constrained_params.contains(&(idx as u32)))
f9f354fc 266 .map(|(_, arg)| arg)
ba9703b0
XL
267 .collect()
268}
269
270/// Check that parameters of the derived impl don't occur more than once in the
271/// equated substs of the base impl.
272///
273/// For example forbid the following:
274///
2b03887a 275/// ```ignore (illustrative)
ba9703b0
XL
276/// impl<A> Tr for A { }
277/// impl<B> Tr for (B, B) { }
2b03887a 278/// ```
ba9703b0
XL
279///
280/// Note that only consider the unconstrained parameters of the base impl:
281///
2b03887a 282/// ```ignore (illustrative)
ba9703b0
XL
283/// impl<S, I: IntoIterator<Item = S>> Tr<S> for I { }
284/// impl<T> Tr<T> for Vec<T> { }
2b03887a 285/// ```
ba9703b0
XL
286///
287/// The substs for the parent impl here are `[T, Vec<T>]`, which repeats `T`,
288/// but `S` is constrained in the parent impl, so `parent_substs` is only
289/// `[Vec<T>]`. This means we allow this impl.
290fn check_duplicate_params<'tcx>(
291 tcx: TyCtxt<'tcx>,
292 impl1_substs: SubstsRef<'tcx>,
293 parent_substs: &Vec<GenericArg<'tcx>>,
294 span: Span,
295) {
5099ac24 296 let mut base_params = cgp::parameters_for(parent_substs, true);
ba9703b0
XL
297 base_params.sort_by_key(|param| param.0);
298 if let (_, [duplicate, ..]) = base_params.partition_dedup() {
299 let param = impl1_substs[duplicate.0 as usize];
300 tcx.sess
49aad941 301 .struct_span_err(span, format!("specializing impl repeats parameter `{}`", param))
ba9703b0
XL
302 .emit();
303 }
304}
305
306/// Check that `'static` lifetimes are not introduced by the specializing impl.
307///
308/// For example forbid the following:
309///
2b03887a 310/// ```ignore (illustrative)
ba9703b0
XL
311/// impl<A> Tr for A { }
312/// impl Tr for &'static i32 { }
2b03887a 313/// ```
ba9703b0
XL
314fn check_static_lifetimes<'tcx>(
315 tcx: TyCtxt<'tcx>,
316 parent_substs: &Vec<GenericArg<'tcx>>,
317 span: Span,
318) {
5099ac24 319 if tcx.any_free_region_meets(parent_substs, |r| r.is_static()) {
49aad941 320 tcx.sess.emit_err(errors::StaticSpecialize { span });
ba9703b0
XL
321 }
322}
323
324/// Check whether predicates on the specializing impl (`impl1`) are allowed.
325///
487cf647 326/// Each predicate `P` must be one of:
ba9703b0 327///
487cf647
FG
328/// * Global (not reference any parameters).
329/// * A `T: Tr` predicate where `Tr` is an always-applicable trait.
330/// * Present on the base impl `impl2`.
331/// * This check is done using the `trait_predicates_eq` function below.
332/// * A well-formed predicate of a type argument of the trait being implemented,
ba9703b0 333/// including the `Self`-type.
487cf647 334#[instrument(level = "debug", skip(tcx))]
ba9703b0 335fn check_predicates<'tcx>(
f2b60f7d 336 tcx: TyCtxt<'tcx>,
f9f354fc 337 impl1_def_id: LocalDefId,
ba9703b0
XL
338 impl1_substs: SubstsRef<'tcx>,
339 impl2_node: Node,
340 impl2_substs: SubstsRef<'tcx>,
341 span: Span,
342) {
064997fb 343 let instantiated = tcx.predicates_of(impl1_def_id).instantiate(tcx, impl1_substs);
353b0b11 344 let impl1_predicates: Vec<_> = traits::elaborate(tcx, instantiated.into_iter()).collect();
c295e0f8 345
ba9703b0
XL
346 let mut impl2_predicates = if impl2_node.is_from_trait() {
347 // Always applicable traits have to be always applicable without any
348 // assumptions.
c295e0f8 349 Vec::new()
ba9703b0 350 } else {
353b0b11 351 traits::elaborate(
c295e0f8
XL
352 tcx,
353 tcx.predicates_of(impl2_node.def_id())
354 .instantiate(tcx, impl2_substs)
355 .predicates
356 .into_iter(),
357 )
c295e0f8 358 .collect()
ba9703b0 359 };
487cf647 360 debug!(?impl1_predicates, ?impl2_predicates);
ba9703b0
XL
361
362 // Since impls of always applicable traits don't get to assume anything, we
363 // can also assume their supertraits apply.
364 //
365 // For example, we allow:
366 //
367 // #[rustc_specialization_trait]
368 // trait AlwaysApplicable: Debug { }
369 //
370 // impl<T> Tr for T { }
371 // impl<T: AlwaysApplicable> Tr for T { }
372 //
373 // Specializing on `AlwaysApplicable` allows also specializing on `Debug`
374 // which is sound because we forbid impls like the following
375 //
376 // impl<D: Debug> AlwaysApplicable for D { }
353b0b11
FG
377 let always_applicable_traits = impl1_predicates
378 .iter()
379 .copied()
380 .filter(|&(predicate, _)| {
381 matches!(
382 trait_predicate_kind(tcx, predicate),
383 Some(TraitSpecializationKind::AlwaysApplicable)
384 )
385 })
386 .map(|(pred, _span)| pred);
ba9703b0
XL
387
388 // Include the well-formed predicates of the type parameters of the impl.
9c376795 389 for arg in tcx.impl_trait_ref(impl1_def_id).unwrap().subst_identity().substs {
2b03887a 390 let infcx = &tcx.infer_ctxt().build();
9ffffee4
FG
391 let obligations =
392 wf::obligations(infcx, tcx.param_env(impl1_def_id), impl1_def_id, 0, arg, span)
393 .unwrap();
f2b60f7d 394
49aad941 395 assert!(!obligations.has_infer());
353b0b11
FG
396 impl2_predicates
397 .extend(traits::elaborate(tcx, obligations).map(|obligation| obligation.predicate))
ba9703b0 398 }
353b0b11 399 impl2_predicates.extend(traits::elaborate(tcx, always_applicable_traits));
ba9703b0 400
064997fb 401 for (predicate, span) in impl1_predicates {
487cf647 402 if !impl2_predicates.iter().any(|pred2| trait_predicates_eq(tcx, predicate, *pred2, span)) {
f9f354fc 403 check_specialization_on(tcx, predicate, span)
ba9703b0
XL
404 }
405 }
406}
407
487cf647
FG
408/// Checks if some predicate on the specializing impl (`predicate1`) is the same
409/// as some predicate on the base impl (`predicate2`).
410///
411/// This basically just checks syntactic equivalence, but is a little more
412/// forgiving since we want to equate `T: Tr` with `T: ~const Tr` so this can work:
413///
414/// ```ignore (illustrative)
415/// #[rustc_specialization_trait]
416/// trait Specialize { }
417///
418/// impl<T: Bound> Tr for T { }
419/// impl<T: ~const Bound + Specialize> const Tr for T { }
420/// ```
421///
422/// However, we *don't* want to allow the reverse, i.e., when the bound on the
423/// specializing impl is not as const as the bound on the base impl:
424///
425/// ```ignore (illustrative)
426/// impl<T: ~const Bound> const Tr for T { }
427/// impl<T: Bound + Specialize> const Tr for T { } // should be T: ~const Bound
428/// ```
429///
430/// So we make that check in this function and try to raise a helpful error message.
431fn trait_predicates_eq<'tcx>(
432 tcx: TyCtxt<'tcx>,
433 predicate1: ty::Predicate<'tcx>,
434 predicate2: ty::Predicate<'tcx>,
435 span: Span,
436) -> bool {
437 let pred1_kind = predicate1.kind().skip_binder();
438 let pred2_kind = predicate2.kind().skip_binder();
439 let (trait_pred1, trait_pred2) = match (pred1_kind, pred2_kind) {
440 (
441 ty::PredicateKind::Clause(ty::Clause::Trait(pred1)),
442 ty::PredicateKind::Clause(ty::Clause::Trait(pred2)),
443 ) => (pred1, pred2),
444 // Just use plain syntactic equivalence if either of the predicates aren't
445 // trait predicates or have bound vars.
446 _ => return predicate1 == predicate2,
447 };
448
449 let predicates_equal_modulo_constness = {
450 let pred1_unconsted =
451 ty::TraitPredicate { constness: ty::BoundConstness::NotConst, ..trait_pred1 };
452 let pred2_unconsted =
453 ty::TraitPredicate { constness: ty::BoundConstness::NotConst, ..trait_pred2 };
454 pred1_unconsted == pred2_unconsted
455 };
456
457 if !predicates_equal_modulo_constness {
458 return false;
459 }
460
461 // Check that the predicate on the specializing impl is at least as const as
462 // the one on the base.
463 match (trait_pred2.constness, trait_pred1.constness) {
464 (ty::BoundConstness::ConstIfConst, ty::BoundConstness::NotConst) => {
49aad941 465 tcx.sess.emit_err(errors::MissingTildeConst { span });
487cf647
FG
466 }
467 _ => {}
468 }
469
470 true
471}
472
473#[instrument(level = "debug", skip(tcx))]
f9f354fc 474fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>, span: Span) {
5869c6ff 475 match predicate.kind().skip_binder() {
ba9703b0
XL
476 // Global predicates are either always true or always false, so we
477 // are fine to specialize on.
5099ac24 478 _ if predicate.is_global() => (),
ba9703b0
XL
479 // We allow specializing on explicitly marked traits with no associated
480 // items.
487cf647 481 ty::PredicateKind::Clause(ty::Clause::Trait(ty::TraitPredicate {
94222f64 482 trait_ref,
487cf647 483 constness: _,
3c0e092e 484 polarity: _,
487cf647 485 })) => {
ba9703b0
XL
486 if !matches!(
487 trait_predicate_kind(tcx, predicate),
488 Some(TraitSpecializationKind::Marker)
489 ) {
490 tcx.sess
491 .struct_span_err(
492 span,
49aad941 493 format!(
ba9703b0 494 "cannot specialize on trait `{}`",
94222f64 495 tcx.def_path_str(trait_ref.def_id),
ba9703b0
XL
496 ),
497 )
5e7ed085 498 .emit();
ba9703b0
XL
499 }
500 }
487cf647
FG
501 ty::PredicateKind::Clause(ty::Clause::Projection(ty::ProjectionPredicate {
502 projection_ty,
503 term,
504 })) => {
064997fb
FG
505 tcx.sess
506 .struct_span_err(
507 span,
49aad941 508 format!("cannot specialize on associated type `{projection_ty} == {term}`",),
064997fb
FG
509 )
510 .emit();
511 }
9ffffee4
FG
512 ty::PredicateKind::Clause(ty::Clause::ConstArgHasType(..)) => {
513 // FIXME(min_specialization), FIXME(const_generics):
514 // It probably isn't right to allow _every_ `ConstArgHasType` but I am somewhat unsure
515 // about the actual rules that would be sound. Can't just always error here because otherwise
516 // std/core doesn't even compile as they have `const N: usize` in some specializing impls.
517 //
518 // While we do not support constructs like `<T, const N: T>` there is probably no risk of
519 // soundness bugs, but when we support generic const parameter types this will need to be
520 // revisited.
521 }
5e7ed085
FG
522 _ => {
523 tcx.sess
49aad941 524 .struct_span_err(span, format!("cannot specialize on predicate `{}`", predicate))
5e7ed085
FG
525 .emit();
526 }
ba9703b0
XL
527 }
528}
529
530fn trait_predicate_kind<'tcx>(
531 tcx: TyCtxt<'tcx>,
f9f354fc 532 predicate: ty::Predicate<'tcx>,
ba9703b0 533) -> Option<TraitSpecializationKind> {
5869c6ff 534 match predicate.kind().skip_binder() {
487cf647
FG
535 ty::PredicateKind::Clause(ty::Clause::Trait(ty::TraitPredicate {
536 trait_ref,
537 constness: _,
538 polarity: _,
539 })) => Some(tcx.trait_def(trait_ref.def_id).specialization_kind),
540 ty::PredicateKind::Clause(ty::Clause::RegionOutlives(_))
541 | ty::PredicateKind::Clause(ty::Clause::TypeOutlives(_))
542 | ty::PredicateKind::Clause(ty::Clause::Projection(_))
9ffffee4 543 | ty::PredicateKind::Clause(ty::Clause::ConstArgHasType(..))
353b0b11 544 | ty::PredicateKind::AliasRelate(..)
5869c6ff
XL
545 | ty::PredicateKind::WellFormed(_)
546 | ty::PredicateKind::Subtype(_)
94222f64 547 | ty::PredicateKind::Coerce(_)
5869c6ff
XL
548 | ty::PredicateKind::ObjectSafe(_)
549 | ty::PredicateKind::ClosureKind(..)
550 | ty::PredicateKind::ConstEvaluatable(..)
551 | ty::PredicateKind::ConstEquate(..)
487cf647 552 | ty::PredicateKind::Ambiguous
5869c6ff 553 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
ba9703b0
XL
554 }
555}