]>
Commit | Line | Data |
---|---|---|
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 | ||
68 | use crate::constrained_generic_params as cgp; | |
04454e1e | 69 | use crate::errors::SubstsOnOverriddenImpl; |
ba9703b0 XL |
70 | |
71 | use rustc_data_structures::fx::FxHashSet; | |
487cf647 | 72 | use rustc_hir as hir; |
f9f354fc | 73 | use rustc_hir::def_id::{DefId, LocalDefId}; |
ba9703b0 | 74 | use rustc_infer::infer::outlives::env::OutlivesEnvironment; |
f2b60f7d | 75 | use rustc_infer::infer::TyCtxtInferExt; |
ba9703b0 | 76 | use rustc_infer::traits::specialization_graph::Node; |
ba9703b0 XL |
77 | use rustc_middle::ty::subst::{GenericArg, InternalSubsts, SubstsRef}; |
78 | use rustc_middle::ty::trait_def::TraitSpecializationKind; | |
9ffffee4 | 79 | use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt}; |
ba9703b0 | 80 | use rustc_span::Span; |
2b03887a | 81 | use rustc_trait_selection::traits::error_reporting::TypeErrCtxtExt; |
f2b60f7d FG |
82 | use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _; |
83 | use rustc_trait_selection::traits::{self, translate_substs, wf, ObligationCtxt}; | |
ba9703b0 | 84 | |
064997fb | 85 | pub(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 | 91 | fn 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 | } | |
103 | Some(impl2_node) | |
104 | } | |
105 | ||
106 | /// Check that `impl1` is a sound specialization | |
487cf647 | 107 | #[instrument(level = "debug", skip(tcx))] |
f2b60f7d FG |
108 | fn check_always_applicable(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node) { |
109 | if let Some((impl1_substs, impl2_substs)) = get_impl_substs(tcx, impl1_def_id, impl2_node) { | |
ba9703b0 | 110 | let impl2_def_id = impl2_node.def_id(); |
487cf647 | 111 | debug!(?impl2_def_id, ?impl2_substs); |
ba9703b0 | 112 | |
ba9703b0 XL |
113 | let parent_substs = if impl2_node.is_from_trait() { |
114 | impl2_substs.to_vec() | |
115 | } else { | |
116 | unconstrained_parent_impl_substs(tcx, impl2_def_id, impl2_substs) | |
117 | }; | |
118 | ||
064997fb | 119 | let span = tcx.def_span(impl1_def_id); |
487cf647 | 120 | check_constness(tcx, impl1_def_id, impl2_node, span); |
ba9703b0 XL |
121 | check_static_lifetimes(tcx, &parent_substs, span); |
122 | check_duplicate_params(tcx, impl1_substs, &parent_substs, span); | |
f2b60f7d | 123 | check_predicates(tcx, impl1_def_id, impl1_substs, impl2_node, impl2_substs, span); |
ba9703b0 XL |
124 | } |
125 | } | |
126 | ||
487cf647 FG |
127 | /// Check that the specializing impl `impl1` is at least as const as the base |
128 | /// impl `impl2` | |
129 | fn check_constness(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node, span: Span) { | |
130 | if impl2_node.is_from_trait() { | |
131 | // This isn't a specialization | |
132 | return; | |
133 | } | |
134 | ||
135 | let impl1_constness = tcx.constness(impl1_def_id.to_def_id()); | |
136 | let impl2_constness = tcx.constness(impl2_node.def_id()); | |
137 | ||
138 | if let hir::Constness::Const = impl2_constness { | |
139 | if let hir::Constness::NotConst = impl1_constness { | |
140 | tcx.sess | |
141 | .struct_span_err(span, "cannot specialize on const impl with non-const impl") | |
142 | .emit(); | |
143 | } | |
144 | } | |
145 | } | |
146 | ||
ba9703b0 XL |
147 | /// Given a specializing impl `impl1`, and the base impl `impl2`, returns two |
148 | /// substitutions `(S1, S2)` that equate their trait references. The returned | |
149 | /// types are expressed in terms of the generics of `impl1`. | |
150 | /// | |
151 | /// Example | |
152 | /// | |
2b03887a | 153 | /// ```ignore (illustrative) |
ba9703b0 XL |
154 | /// impl<A, B> Foo<A> for B { /* impl2 */ } |
155 | /// impl<C> Foo<Vec<C>> for C { /* impl1 */ } | |
2b03887a | 156 | /// ``` |
ba9703b0 XL |
157 | /// |
158 | /// Would return `S1 = [C]` and `S2 = [Vec<C>, C]`. | |
9c376795 FG |
159 | fn get_impl_substs( |
160 | tcx: TyCtxt<'_>, | |
064997fb | 161 | impl1_def_id: LocalDefId, |
ba9703b0 | 162 | impl2_node: Node, |
9c376795 | 163 | ) -> Option<(SubstsRef<'_>, SubstsRef<'_>)> { |
2b03887a FG |
164 | let infcx = &tcx.infer_ctxt().build(); |
165 | let ocx = ObligationCtxt::new(infcx); | |
166 | let param_env = tcx.param_env(impl1_def_id); | |
ba9703b0 | 167 | |
2b03887a FG |
168 | let assumed_wf_types = |
169 | ocx.assumed_wf_types(param_env, tcx.def_span(impl1_def_id), impl1_def_id); | |
ba9703b0 | 170 | |
353b0b11 | 171 | let impl1_substs = InternalSubsts::identity_for_item(tcx, impl1_def_id); |
2b03887a FG |
172 | let impl2_substs = |
173 | translate_substs(infcx, param_env, impl1_def_id.to_def_id(), impl1_substs, impl2_node); | |
f2b60f7d | 174 | |
2b03887a FG |
175 | let errors = ocx.select_all_or_error(); |
176 | if !errors.is_empty() { | |
353b0b11 | 177 | ocx.infcx.err_ctxt().report_fulfillment_errors(&errors); |
2b03887a FG |
178 | return None; |
179 | } | |
f2b60f7d | 180 | |
9ffffee4 | 181 | let implied_bounds = infcx.implied_bounds_tys(param_env, impl1_def_id, assumed_wf_types); |
353b0b11 FG |
182 | let outlives_env = OutlivesEnvironment::with_bounds(param_env, implied_bounds); |
183 | let _ = ocx.resolve_regions_and_report_errors(impl1_def_id, &outlives_env); | |
2b03887a FG |
184 | let Ok(impl2_substs) = infcx.fully_resolve(impl2_substs) else { |
185 | let span = tcx.def_span(impl1_def_id); | |
186 | tcx.sess.emit_err(SubstsOnOverriddenImpl { span }); | |
187 | return None; | |
188 | }; | |
189 | Some((impl1_substs, impl2_substs)) | |
ba9703b0 XL |
190 | } |
191 | ||
192 | /// Returns a list of all of the unconstrained subst of the given impl. | |
193 | /// | |
194 | /// For example given the impl: | |
195 | /// | |
196 | /// impl<'a, T, I> ... where &'a I: IntoIterator<Item=&'a T> | |
197 | /// | |
198 | /// This would return the substs corresponding to `['a, I]`, because knowing | |
199 | /// `'a` and `I` determines the value of `T`. | |
200 | fn unconstrained_parent_impl_substs<'tcx>( | |
201 | tcx: TyCtxt<'tcx>, | |
202 | impl_def_id: DefId, | |
203 | impl_substs: SubstsRef<'tcx>, | |
204 | ) -> Vec<GenericArg<'tcx>> { | |
205 | let impl_generic_predicates = tcx.predicates_of(impl_def_id); | |
206 | let mut unconstrained_parameters = FxHashSet::default(); | |
207 | let mut constrained_params = FxHashSet::default(); | |
9c376795 | 208 | let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).map(ty::EarlyBinder::subst_identity); |
ba9703b0 XL |
209 | |
210 | // Unfortunately the functions in `constrained_generic_parameters` don't do | |
211 | // what we want here. We want only a list of constrained parameters while | |
212 | // the functions in `cgp` add the constrained parameters to a list of | |
213 | // unconstrained parameters. | |
214 | for (predicate, _) in impl_generic_predicates.predicates.iter() { | |
487cf647 FG |
215 | if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) = |
216 | predicate.kind().skip_binder() | |
217 | { | |
3dfed10e | 218 | let projection_ty = proj.projection_ty; |
5099ac24 | 219 | let projected_ty = proj.term; |
ba9703b0 XL |
220 | |
221 | let unbound_trait_ref = projection_ty.trait_ref(tcx); | |
222 | if Some(unbound_trait_ref) == impl_trait_ref { | |
223 | continue; | |
224 | } | |
225 | ||
5099ac24 | 226 | unconstrained_parameters.extend(cgp::parameters_for(&projection_ty, true)); |
ba9703b0 | 227 | |
5099ac24 | 228 | for param in cgp::parameters_for(&projected_ty, false) { |
ba9703b0 XL |
229 | if !unconstrained_parameters.contains(¶m) { |
230 | constrained_params.insert(param.0); | |
231 | } | |
232 | } | |
233 | ||
5099ac24 | 234 | unconstrained_parameters.extend(cgp::parameters_for(&projected_ty, true)); |
ba9703b0 XL |
235 | } |
236 | } | |
237 | ||
238 | impl_substs | |
239 | .iter() | |
240 | .enumerate() | |
241 | .filter(|&(idx, _)| !constrained_params.contains(&(idx as u32))) | |
f9f354fc | 242 | .map(|(_, arg)| arg) |
ba9703b0 XL |
243 | .collect() |
244 | } | |
245 | ||
246 | /// Check that parameters of the derived impl don't occur more than once in the | |
247 | /// equated substs of the base impl. | |
248 | /// | |
249 | /// For example forbid the following: | |
250 | /// | |
2b03887a | 251 | /// ```ignore (illustrative) |
ba9703b0 XL |
252 | /// impl<A> Tr for A { } |
253 | /// impl<B> Tr for (B, B) { } | |
2b03887a | 254 | /// ``` |
ba9703b0 XL |
255 | /// |
256 | /// Note that only consider the unconstrained parameters of the base impl: | |
257 | /// | |
2b03887a | 258 | /// ```ignore (illustrative) |
ba9703b0 XL |
259 | /// impl<S, I: IntoIterator<Item = S>> Tr<S> for I { } |
260 | /// impl<T> Tr<T> for Vec<T> { } | |
2b03887a | 261 | /// ``` |
ba9703b0 XL |
262 | /// |
263 | /// The substs for the parent impl here are `[T, Vec<T>]`, which repeats `T`, | |
264 | /// but `S` is constrained in the parent impl, so `parent_substs` is only | |
265 | /// `[Vec<T>]`. This means we allow this impl. | |
266 | fn check_duplicate_params<'tcx>( | |
267 | tcx: TyCtxt<'tcx>, | |
268 | impl1_substs: SubstsRef<'tcx>, | |
269 | parent_substs: &Vec<GenericArg<'tcx>>, | |
270 | span: Span, | |
271 | ) { | |
5099ac24 | 272 | let mut base_params = cgp::parameters_for(parent_substs, true); |
ba9703b0 XL |
273 | base_params.sort_by_key(|param| param.0); |
274 | if let (_, [duplicate, ..]) = base_params.partition_dedup() { | |
275 | let param = impl1_substs[duplicate.0 as usize]; | |
276 | tcx.sess | |
277 | .struct_span_err(span, &format!("specializing impl repeats parameter `{}`", param)) | |
278 | .emit(); | |
279 | } | |
280 | } | |
281 | ||
282 | /// Check that `'static` lifetimes are not introduced by the specializing impl. | |
283 | /// | |
284 | /// For example forbid the following: | |
285 | /// | |
2b03887a | 286 | /// ```ignore (illustrative) |
ba9703b0 XL |
287 | /// impl<A> Tr for A { } |
288 | /// impl Tr for &'static i32 { } | |
2b03887a | 289 | /// ``` |
ba9703b0 XL |
290 | fn check_static_lifetimes<'tcx>( |
291 | tcx: TyCtxt<'tcx>, | |
292 | parent_substs: &Vec<GenericArg<'tcx>>, | |
293 | span: Span, | |
294 | ) { | |
5099ac24 | 295 | if tcx.any_free_region_meets(parent_substs, |r| r.is_static()) { |
ba9703b0 XL |
296 | tcx.sess.struct_span_err(span, "cannot specialize on `'static` lifetime").emit(); |
297 | } | |
298 | } | |
299 | ||
300 | /// Check whether predicates on the specializing impl (`impl1`) are allowed. | |
301 | /// | |
487cf647 | 302 | /// Each predicate `P` must be one of: |
ba9703b0 | 303 | /// |
487cf647 FG |
304 | /// * Global (not reference any parameters). |
305 | /// * A `T: Tr` predicate where `Tr` is an always-applicable trait. | |
306 | /// * Present on the base impl `impl2`. | |
307 | /// * This check is done using the `trait_predicates_eq` function below. | |
308 | /// * A well-formed predicate of a type argument of the trait being implemented, | |
ba9703b0 | 309 | /// including the `Self`-type. |
487cf647 | 310 | #[instrument(level = "debug", skip(tcx))] |
ba9703b0 | 311 | fn check_predicates<'tcx>( |
f2b60f7d | 312 | tcx: TyCtxt<'tcx>, |
f9f354fc | 313 | impl1_def_id: LocalDefId, |
ba9703b0 XL |
314 | impl1_substs: SubstsRef<'tcx>, |
315 | impl2_node: Node, | |
316 | impl2_substs: SubstsRef<'tcx>, | |
317 | span: Span, | |
318 | ) { | |
064997fb | 319 | let instantiated = tcx.predicates_of(impl1_def_id).instantiate(tcx, impl1_substs); |
353b0b11 | 320 | let impl1_predicates: Vec<_> = traits::elaborate(tcx, instantiated.into_iter()).collect(); |
c295e0f8 | 321 | |
ba9703b0 XL |
322 | let mut impl2_predicates = if impl2_node.is_from_trait() { |
323 | // Always applicable traits have to be always applicable without any | |
324 | // assumptions. | |
c295e0f8 | 325 | Vec::new() |
ba9703b0 | 326 | } else { |
353b0b11 | 327 | traits::elaborate( |
c295e0f8 XL |
328 | tcx, |
329 | tcx.predicates_of(impl2_node.def_id()) | |
330 | .instantiate(tcx, impl2_substs) | |
331 | .predicates | |
332 | .into_iter(), | |
333 | ) | |
c295e0f8 | 334 | .collect() |
ba9703b0 | 335 | }; |
487cf647 | 336 | debug!(?impl1_predicates, ?impl2_predicates); |
ba9703b0 XL |
337 | |
338 | // Since impls of always applicable traits don't get to assume anything, we | |
339 | // can also assume their supertraits apply. | |
340 | // | |
341 | // For example, we allow: | |
342 | // | |
343 | // #[rustc_specialization_trait] | |
344 | // trait AlwaysApplicable: Debug { } | |
345 | // | |
346 | // impl<T> Tr for T { } | |
347 | // impl<T: AlwaysApplicable> Tr for T { } | |
348 | // | |
349 | // Specializing on `AlwaysApplicable` allows also specializing on `Debug` | |
350 | // which is sound because we forbid impls like the following | |
351 | // | |
352 | // impl<D: Debug> AlwaysApplicable for D { } | |
353b0b11 FG |
353 | let always_applicable_traits = impl1_predicates |
354 | .iter() | |
355 | .copied() | |
356 | .filter(|&(predicate, _)| { | |
357 | matches!( | |
358 | trait_predicate_kind(tcx, predicate), | |
359 | Some(TraitSpecializationKind::AlwaysApplicable) | |
360 | ) | |
361 | }) | |
362 | .map(|(pred, _span)| pred); | |
ba9703b0 XL |
363 | |
364 | // Include the well-formed predicates of the type parameters of the impl. | |
9c376795 | 365 | for arg in tcx.impl_trait_ref(impl1_def_id).unwrap().subst_identity().substs { |
2b03887a | 366 | let infcx = &tcx.infer_ctxt().build(); |
9ffffee4 FG |
367 | let obligations = |
368 | wf::obligations(infcx, tcx.param_env(impl1_def_id), impl1_def_id, 0, arg, span) | |
369 | .unwrap(); | |
f2b60f7d | 370 | |
2b03887a | 371 | assert!(!obligations.needs_infer()); |
353b0b11 FG |
372 | impl2_predicates |
373 | .extend(traits::elaborate(tcx, obligations).map(|obligation| obligation.predicate)) | |
ba9703b0 | 374 | } |
353b0b11 | 375 | impl2_predicates.extend(traits::elaborate(tcx, always_applicable_traits)); |
ba9703b0 | 376 | |
064997fb | 377 | for (predicate, span) in impl1_predicates { |
487cf647 | 378 | if !impl2_predicates.iter().any(|pred2| trait_predicates_eq(tcx, predicate, *pred2, span)) { |
f9f354fc | 379 | check_specialization_on(tcx, predicate, span) |
ba9703b0 XL |
380 | } |
381 | } | |
382 | } | |
383 | ||
487cf647 FG |
384 | /// Checks if some predicate on the specializing impl (`predicate1`) is the same |
385 | /// as some predicate on the base impl (`predicate2`). | |
386 | /// | |
387 | /// This basically just checks syntactic equivalence, but is a little more | |
388 | /// forgiving since we want to equate `T: Tr` with `T: ~const Tr` so this can work: | |
389 | /// | |
390 | /// ```ignore (illustrative) | |
391 | /// #[rustc_specialization_trait] | |
392 | /// trait Specialize { } | |
393 | /// | |
394 | /// impl<T: Bound> Tr for T { } | |
395 | /// impl<T: ~const Bound + Specialize> const Tr for T { } | |
396 | /// ``` | |
397 | /// | |
398 | /// However, we *don't* want to allow the reverse, i.e., when the bound on the | |
399 | /// specializing impl is not as const as the bound on the base impl: | |
400 | /// | |
401 | /// ```ignore (illustrative) | |
402 | /// impl<T: ~const Bound> const Tr for T { } | |
403 | /// impl<T: Bound + Specialize> const Tr for T { } // should be T: ~const Bound | |
404 | /// ``` | |
405 | /// | |
406 | /// So we make that check in this function and try to raise a helpful error message. | |
407 | fn trait_predicates_eq<'tcx>( | |
408 | tcx: TyCtxt<'tcx>, | |
409 | predicate1: ty::Predicate<'tcx>, | |
410 | predicate2: ty::Predicate<'tcx>, | |
411 | span: Span, | |
412 | ) -> bool { | |
413 | let pred1_kind = predicate1.kind().skip_binder(); | |
414 | let pred2_kind = predicate2.kind().skip_binder(); | |
415 | let (trait_pred1, trait_pred2) = match (pred1_kind, pred2_kind) { | |
416 | ( | |
417 | ty::PredicateKind::Clause(ty::Clause::Trait(pred1)), | |
418 | ty::PredicateKind::Clause(ty::Clause::Trait(pred2)), | |
419 | ) => (pred1, pred2), | |
420 | // Just use plain syntactic equivalence if either of the predicates aren't | |
421 | // trait predicates or have bound vars. | |
422 | _ => return predicate1 == predicate2, | |
423 | }; | |
424 | ||
425 | let predicates_equal_modulo_constness = { | |
426 | let pred1_unconsted = | |
427 | ty::TraitPredicate { constness: ty::BoundConstness::NotConst, ..trait_pred1 }; | |
428 | let pred2_unconsted = | |
429 | ty::TraitPredicate { constness: ty::BoundConstness::NotConst, ..trait_pred2 }; | |
430 | pred1_unconsted == pred2_unconsted | |
431 | }; | |
432 | ||
433 | if !predicates_equal_modulo_constness { | |
434 | return false; | |
435 | } | |
436 | ||
437 | // Check that the predicate on the specializing impl is at least as const as | |
438 | // the one on the base. | |
439 | match (trait_pred2.constness, trait_pred1.constness) { | |
440 | (ty::BoundConstness::ConstIfConst, ty::BoundConstness::NotConst) => { | |
441 | tcx.sess.struct_span_err(span, "missing `~const` qualifier for specialization").emit(); | |
442 | } | |
443 | _ => {} | |
444 | } | |
445 | ||
446 | true | |
447 | } | |
448 | ||
449 | #[instrument(level = "debug", skip(tcx))] | |
f9f354fc | 450 | fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>, span: Span) { |
5869c6ff | 451 | match predicate.kind().skip_binder() { |
ba9703b0 XL |
452 | // Global predicates are either always true or always false, so we |
453 | // are fine to specialize on. | |
5099ac24 | 454 | _ if predicate.is_global() => (), |
ba9703b0 XL |
455 | // We allow specializing on explicitly marked traits with no associated |
456 | // items. | |
487cf647 | 457 | ty::PredicateKind::Clause(ty::Clause::Trait(ty::TraitPredicate { |
94222f64 | 458 | trait_ref, |
487cf647 | 459 | constness: _, |
3c0e092e | 460 | polarity: _, |
487cf647 | 461 | })) => { |
ba9703b0 XL |
462 | if !matches!( |
463 | trait_predicate_kind(tcx, predicate), | |
464 | Some(TraitSpecializationKind::Marker) | |
465 | ) { | |
466 | tcx.sess | |
467 | .struct_span_err( | |
468 | span, | |
469 | &format!( | |
470 | "cannot specialize on trait `{}`", | |
94222f64 | 471 | tcx.def_path_str(trait_ref.def_id), |
ba9703b0 XL |
472 | ), |
473 | ) | |
5e7ed085 | 474 | .emit(); |
ba9703b0 XL |
475 | } |
476 | } | |
487cf647 FG |
477 | ty::PredicateKind::Clause(ty::Clause::Projection(ty::ProjectionPredicate { |
478 | projection_ty, | |
479 | term, | |
480 | })) => { | |
064997fb FG |
481 | tcx.sess |
482 | .struct_span_err( | |
483 | span, | |
484 | &format!("cannot specialize on associated type `{projection_ty} == {term}`",), | |
485 | ) | |
486 | .emit(); | |
487 | } | |
9ffffee4 FG |
488 | ty::PredicateKind::Clause(ty::Clause::ConstArgHasType(..)) => { |
489 | // FIXME(min_specialization), FIXME(const_generics): | |
490 | // It probably isn't right to allow _every_ `ConstArgHasType` but I am somewhat unsure | |
491 | // about the actual rules that would be sound. Can't just always error here because otherwise | |
492 | // std/core doesn't even compile as they have `const N: usize` in some specializing impls. | |
493 | // | |
494 | // While we do not support constructs like `<T, const N: T>` there is probably no risk of | |
495 | // soundness bugs, but when we support generic const parameter types this will need to be | |
496 | // revisited. | |
497 | } | |
5e7ed085 FG |
498 | _ => { |
499 | tcx.sess | |
064997fb | 500 | .struct_span_err(span, &format!("cannot specialize on predicate `{}`", predicate)) |
5e7ed085 FG |
501 | .emit(); |
502 | } | |
ba9703b0 XL |
503 | } |
504 | } | |
505 | ||
506 | fn trait_predicate_kind<'tcx>( | |
507 | tcx: TyCtxt<'tcx>, | |
f9f354fc | 508 | predicate: ty::Predicate<'tcx>, |
ba9703b0 | 509 | ) -> Option<TraitSpecializationKind> { |
5869c6ff | 510 | match predicate.kind().skip_binder() { |
487cf647 FG |
511 | ty::PredicateKind::Clause(ty::Clause::Trait(ty::TraitPredicate { |
512 | trait_ref, | |
513 | constness: _, | |
514 | polarity: _, | |
515 | })) => Some(tcx.trait_def(trait_ref.def_id).specialization_kind), | |
516 | ty::PredicateKind::Clause(ty::Clause::RegionOutlives(_)) | |
517 | | ty::PredicateKind::Clause(ty::Clause::TypeOutlives(_)) | |
518 | | ty::PredicateKind::Clause(ty::Clause::Projection(_)) | |
9ffffee4 | 519 | | ty::PredicateKind::Clause(ty::Clause::ConstArgHasType(..)) |
353b0b11 | 520 | | ty::PredicateKind::AliasRelate(..) |
5869c6ff XL |
521 | | ty::PredicateKind::WellFormed(_) |
522 | | ty::PredicateKind::Subtype(_) | |
94222f64 | 523 | | ty::PredicateKind::Coerce(_) |
5869c6ff XL |
524 | | ty::PredicateKind::ObjectSafe(_) |
525 | | ty::PredicateKind::ClosureKind(..) | |
526 | | ty::PredicateKind::ConstEvaluatable(..) | |
527 | | ty::PredicateKind::ConstEquate(..) | |
487cf647 | 528 | | ty::PredicateKind::Ambiguous |
5869c6ff | 529 | | ty::PredicateKind::TypeWellFormedFromEnv(..) => None, |
ba9703b0 XL |
530 | } |
531 | } |