]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/impl_wf_check/min_specialization.rs
64cd69750f3512cfb44e2080829feb371db82eee
[rust.git] / compiler / rustc_typeck / src / impl_wf_check / min_specialization.rs
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 //!
32 //! ```ignore (illustrative)
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;
69 use crate::errors::SubstsOnOverriddenImpl;
70 use crate::outlives::outlives_bounds::InferCtxtExt;
71
72 use rustc_data_structures::fx::FxHashSet;
73 use rustc_hir::def_id::{DefId, LocalDefId};
74 use rustc_infer::infer::outlives::env::OutlivesEnvironment;
75 use rustc_infer::infer::TyCtxtInferExt;
76 use rustc_infer::traits::specialization_graph::Node;
77 use rustc_middle::ty::subst::{GenericArg, InternalSubsts, SubstsRef};
78 use rustc_middle::ty::trait_def::TraitSpecializationKind;
79 use rustc_middle::ty::{self, TyCtxt, TypeVisitable};
80 use rustc_span::Span;
81 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
82 use rustc_trait_selection::traits::{self, translate_substs, wf, ObligationCtxt};
83
84 pub(super) fn check_min_specialization(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) {
85     if let Some(node) = parent_specialization_node(tcx, impl_def_id) {
86         check_always_applicable(tcx, impl_def_id, node);
87     }
88 }
89
90 fn parent_specialization_node(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId) -> Option<Node> {
91     let trait_ref = tcx.impl_trait_ref(impl1_def_id)?;
92     let trait_def = tcx.trait_def(trait_ref.def_id);
93
94     let impl2_node = trait_def.ancestors(tcx, impl1_def_id.to_def_id()).ok()?.nth(1)?;
95
96     let always_applicable_trait =
97         matches!(trait_def.specialization_kind, TraitSpecializationKind::AlwaysApplicable);
98     if impl2_node.is_from_trait() && !always_applicable_trait {
99         // Implementing a normal trait isn't a specialization.
100         return None;
101     }
102     Some(impl2_node)
103 }
104
105 /// Check that `impl1` is a sound specialization
106 fn check_always_applicable(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId, impl2_node: Node) {
107     if let Some((impl1_substs, impl2_substs)) = get_impl_substs(tcx, impl1_def_id, impl2_node) {
108         let impl2_def_id = impl2_node.def_id();
109         debug!(
110             "check_always_applicable(\nimpl1_def_id={:?},\nimpl2_def_id={:?},\nimpl2_substs={:?}\n)",
111             impl1_def_id, impl2_def_id, impl2_substs
112         );
113
114         let parent_substs = if impl2_node.is_from_trait() {
115             impl2_substs.to_vec()
116         } else {
117             unconstrained_parent_impl_substs(tcx, impl2_def_id, impl2_substs)
118         };
119
120         let span = tcx.def_span(impl1_def_id);
121         check_static_lifetimes(tcx, &parent_substs, span);
122         check_duplicate_params(tcx, impl1_substs, &parent_substs, span);
123         check_predicates(tcx, impl1_def_id, impl1_substs, impl2_node, impl2_substs, span);
124     }
125 }
126
127 /// Given a specializing impl `impl1`, and the base impl `impl2`, returns two
128 /// substitutions `(S1, S2)` that equate their trait references. The returned
129 /// types are expressed in terms of the generics of `impl1`.
130 ///
131 /// Example
132 ///
133 /// impl<A, B> Foo<A> for B { /* impl2 */ }
134 /// impl<C> Foo<Vec<C>> for C { /* impl1 */ }
135 ///
136 /// Would return `S1 = [C]` and `S2 = [Vec<C>, C]`.
137 fn get_impl_substs<'tcx>(
138     tcx: TyCtxt<'tcx>,
139     impl1_def_id: LocalDefId,
140     impl2_node: Node,
141 ) -> Option<(SubstsRef<'tcx>, SubstsRef<'tcx>)> {
142     tcx.infer_ctxt().enter(|ref infcx| {
143         let ocx = ObligationCtxt::new(infcx);
144         let param_env = tcx.param_env(impl1_def_id);
145         let impl1_hir_id = tcx.hir().local_def_id_to_hir_id(impl1_def_id);
146
147         let assumed_wf_types =
148             ocx.assumed_wf_types(param_env, tcx.def_span(impl1_def_id), impl1_def_id);
149
150       let impl1_substs = InternalSubsts::identity_for_item(tcx, impl1_def_id.to_def_id());
151         let impl2_substs =
152             translate_substs(infcx, param_env, impl1_def_id.to_def_id(), impl1_substs, impl2_node);
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171         let errors = ocx.select_all_or_error();
172         if !errors.is_empty() {
173             ocx.infcx.report_fulfillment_errors(&errors, None, false);
174             return None;
175         }
176
177         let mut outlives_env = OutlivesEnvironment::new(param_env);
178         outlives_env.add_implied_bounds(infcx, assumed_wf_types, impl1_hir_id);
179         infcx.check_region_obligations_and_report_errors(impl1_def_id, &outlives_env);
180         let Ok(impl2_substs) = infcx.fully_resolve(impl2_substs) else {
181             let span = tcx.def_span(impl1_def_id);
182             tcx.sess.emit_err(SubstsOnOverriddenImpl { span });
183             return None;
184         };
185         Some((impl1_substs, impl2_substs))
186     })}
187
188 /// Returns a list of all of the unconstrained subst of the given impl.
189 ///
190 /// For example given the impl:
191 ///
192 /// impl<'a, T, I> ... where &'a I: IntoIterator<Item=&'a T>
193 ///
194 /// This would return the substs corresponding to `['a, I]`, because knowing
195 /// `'a` and `I` determines the value of `T`.
196 fn unconstrained_parent_impl_substs<'tcx>(
197     tcx: TyCtxt<'tcx>,
198     impl_def_id: DefId,
199     impl_substs: SubstsRef<'tcx>,
200 ) -> Vec<GenericArg<'tcx>> {
201     let impl_generic_predicates = tcx.predicates_of(impl_def_id);
202     let mut unconstrained_parameters = FxHashSet::default();
203     let mut constrained_params = FxHashSet::default();
204     let impl_trait_ref = tcx.impl_trait_ref(impl_def_id);
205
206     // Unfortunately the functions in `constrained_generic_parameters` don't do
207     // what we want here. We want only a list of constrained parameters while
208     // the functions in `cgp` add the constrained parameters to a list of
209     // unconstrained parameters.
210     for (predicate, _) in impl_generic_predicates.predicates.iter() {
211         if let ty::PredicateKind::Projection(proj) = predicate.kind().skip_binder() {
212             let projection_ty = proj.projection_ty;
213             let projected_ty = proj.term;
214
215             let unbound_trait_ref = projection_ty.trait_ref(tcx);
216             if Some(unbound_trait_ref) == impl_trait_ref {
217                 continue;
218             }
219
220             unconstrained_parameters.extend(cgp::parameters_for(&projection_ty, true));
221
222             for param in cgp::parameters_for(&projected_ty, false) {
223                 if !unconstrained_parameters.contains(&param) {
224                     constrained_params.insert(param.0);
225                 }
226             }
227
228             unconstrained_parameters.extend(cgp::parameters_for(&projected_ty, true));
229         }
230     }
231
232     impl_substs
233         .iter()
234         .enumerate()
235         .filter(|&(idx, _)| !constrained_params.contains(&(idx as u32)))
236         .map(|(_, arg)| arg)
237         .collect()
238 }
239
240 /// Check that parameters of the derived impl don't occur more than once in the
241 /// equated substs of the base impl.
242 ///
243 /// For example forbid the following:
244 ///
245 /// impl<A> Tr for A { }
246 /// impl<B> Tr for (B, B) { }
247 ///
248 /// Note that only consider the unconstrained parameters of the base impl:
249 ///
250 /// impl<S, I: IntoIterator<Item = S>> Tr<S> for I { }
251 /// impl<T> Tr<T> for Vec<T> { }
252 ///
253 /// The substs for the parent impl here are `[T, Vec<T>]`, which repeats `T`,
254 /// but `S` is constrained in the parent impl, so `parent_substs` is only
255 /// `[Vec<T>]`. This means we allow this impl.
256 fn check_duplicate_params<'tcx>(
257     tcx: TyCtxt<'tcx>,
258     impl1_substs: SubstsRef<'tcx>,
259     parent_substs: &Vec<GenericArg<'tcx>>,
260     span: Span,
261 ) {
262     let mut base_params = cgp::parameters_for(parent_substs, true);
263     base_params.sort_by_key(|param| param.0);
264     if let (_, [duplicate, ..]) = base_params.partition_dedup() {
265         let param = impl1_substs[duplicate.0 as usize];
266         tcx.sess
267             .struct_span_err(span, &format!("specializing impl repeats parameter `{}`", param))
268             .emit();
269     }
270 }
271
272 /// Check that `'static` lifetimes are not introduced by the specializing impl.
273 ///
274 /// For example forbid the following:
275 ///
276 /// impl<A> Tr for A { }
277 /// impl Tr for &'static i32 { }
278 fn check_static_lifetimes<'tcx>(
279     tcx: TyCtxt<'tcx>,
280     parent_substs: &Vec<GenericArg<'tcx>>,
281     span: Span,
282 ) {
283     if tcx.any_free_region_meets(parent_substs, |r| r.is_static()) {
284         tcx.sess.struct_span_err(span, "cannot specialize on `'static` lifetime").emit();
285     }
286 }
287
288 /// Check whether predicates on the specializing impl (`impl1`) are allowed.
289 ///
290 /// Each predicate `P` must be:
291 ///
292 /// * global (not reference any parameters)
293 /// * `T: Tr` predicate where `Tr` is an always-applicable trait
294 /// * on the base `impl impl2`
295 ///     * Currently this check is done using syntactic equality, which is
296 ///       conservative but generally sufficient.
297 /// * a well-formed predicate of a type argument of the trait being implemented,
298 ///   including the `Self`-type.
299 fn check_predicates<'tcx>(
300     tcx: TyCtxt<'tcx>,
301     impl1_def_id: LocalDefId,
302     impl1_substs: SubstsRef<'tcx>,
303     impl2_node: Node,
304     impl2_substs: SubstsRef<'tcx>,
305     span: Span,
306 ) {
307     let instantiated = tcx.predicates_of(impl1_def_id).instantiate(tcx, impl1_substs);
308     let impl1_predicates: Vec<_> = traits::elaborate_predicates_with_span(
309         tcx,
310         std::iter::zip(
311             instantiated.predicates,
312             // Don't drop predicates (unsound!) because `spans` is too short
313             instantiated.spans.into_iter().chain(std::iter::repeat(span)),
314         ),
315     )
316     .map(|obligation| (obligation.predicate, obligation.cause.span))
317     .collect();
318
319     let mut impl2_predicates = if impl2_node.is_from_trait() {
320         // Always applicable traits have to be always applicable without any
321         // assumptions.
322         Vec::new()
323     } else {
324         traits::elaborate_predicates(
325             tcx,
326             tcx.predicates_of(impl2_node.def_id())
327                 .instantiate(tcx, impl2_substs)
328                 .predicates
329                 .into_iter(),
330         )
331         .map(|obligation| obligation.predicate)
332         .collect()
333     };
334     debug!(
335         "check_always_applicable(\nimpl1_predicates={:?},\nimpl2_predicates={:?}\n)",
336         impl1_predicates, impl2_predicates,
337     );
338
339     // Since impls of always applicable traits don't get to assume anything, we
340     // can also assume their supertraits apply.
341     //
342     // For example, we allow:
343     //
344     // #[rustc_specialization_trait]
345     // trait AlwaysApplicable: Debug { }
346     //
347     // impl<T> Tr for T { }
348     // impl<T: AlwaysApplicable> Tr for T { }
349     //
350     // Specializing on `AlwaysApplicable` allows also specializing on `Debug`
351     // which is sound because we forbid impls like the following
352     //
353     // impl<D: Debug> AlwaysApplicable for D { }
354     let always_applicable_traits = impl1_predicates.iter().copied().filter(|&(predicate, _)| {
355         matches!(
356             trait_predicate_kind(tcx, predicate),
357             Some(TraitSpecializationKind::AlwaysApplicable)
358         )
359     });
360
361     // Include the well-formed predicates of the type parameters of the impl.
362     for arg in tcx.impl_trait_ref(impl1_def_id).unwrap().substs {
363         tcx.infer_ctxt().enter(|ref infcx| {
364             let obligations = wf::obligations(
365                 infcx,
366                 tcx.param_env(impl1_def_id),
367                 tcx.hir().local_def_id_to_hir_id(impl1_def_id),
368                 0,
369                 arg,
370                 span,
371             )
372             .unwrap();
373
374             assert!(!obligations.needs_infer());
375             impl2_predicates.extend(
376                 traits::elaborate_obligations(tcx, obligations)
377                     .map(|obligation| obligation.predicate),
378             )
379         })
380     }
381     impl2_predicates.extend(
382         traits::elaborate_predicates_with_span(tcx, always_applicable_traits)
383             .map(|obligation| obligation.predicate),
384     );
385
386     for (predicate, span) in impl1_predicates {
387         if !impl2_predicates.contains(&predicate) {
388             check_specialization_on(tcx, predicate, span)
389         }
390     }
391 }
392
393 fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>, span: Span) {
394     debug!("can_specialize_on(predicate = {:?})", predicate);
395     match predicate.kind().skip_binder() {
396         // Global predicates are either always true or always false, so we
397         // are fine to specialize on.
398         _ if predicate.is_global() => (),
399         // We allow specializing on explicitly marked traits with no associated
400         // items.
401         ty::PredicateKind::Trait(ty::TraitPredicate {
402             trait_ref,
403             constness: ty::BoundConstness::NotConst,
404             polarity: _,
405         }) => {
406             if !matches!(
407                 trait_predicate_kind(tcx, predicate),
408                 Some(TraitSpecializationKind::Marker)
409             ) {
410                 tcx.sess
411                     .struct_span_err(
412                         span,
413                         &format!(
414                             "cannot specialize on trait `{}`",
415                             tcx.def_path_str(trait_ref.def_id),
416                         ),
417                     )
418                     .emit();
419             }
420         }
421         ty::PredicateKind::Projection(ty::ProjectionPredicate { projection_ty, term }) => {
422             tcx.sess
423                 .struct_span_err(
424                     span,
425                     &format!("cannot specialize on associated type `{projection_ty} == {term}`",),
426                 )
427                 .emit();
428         }
429         _ => {
430             tcx.sess
431                 .struct_span_err(span, &format!("cannot specialize on predicate `{}`", predicate))
432                 .emit();
433         }
434     }
435 }
436
437 fn trait_predicate_kind<'tcx>(
438     tcx: TyCtxt<'tcx>,
439     predicate: ty::Predicate<'tcx>,
440 ) -> Option<TraitSpecializationKind> {
441     match predicate.kind().skip_binder() {
442         ty::PredicateKind::Trait(ty::TraitPredicate {
443             trait_ref,
444             constness: ty::BoundConstness::NotConst,
445             polarity: _,
446         }) => Some(tcx.trait_def(trait_ref.def_id).specialization_kind),
447         ty::PredicateKind::Trait(_)
448         | ty::PredicateKind::RegionOutlives(_)
449         | ty::PredicateKind::TypeOutlives(_)
450         | ty::PredicateKind::Projection(_)
451         | ty::PredicateKind::WellFormed(_)
452         | ty::PredicateKind::Subtype(_)
453         | ty::PredicateKind::Coerce(_)
454         | ty::PredicateKind::ObjectSafe(_)
455         | ty::PredicateKind::ClosureKind(..)
456         | ty::PredicateKind::ConstEvaluatable(..)
457         | ty::PredicateKind::ConstEquate(..)
458         | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
459     }
460 }