]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/impl_wf_check/min_specialization.rs
Rollup merge of #107171 - petrochenkov:encattrs, r=cjgillot
[rust.git] / compiler / rustc_hir_analysis / 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
71 use rustc_data_structures::fx::FxHashSet;
72 use rustc_hir as hir;
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::TypeErrCtxtExt;
82 use rustc_trait_selection::traits::outlives_bounds::InferCtxtExt as _;
83 use rustc_trait_selection::traits::{self, translate_substs, wf, ObligationCtxt};
84
85 pub(super) fn check_min_specialization(tcx: TyCtxt<'_>, impl_def_id: LocalDefId) {
86     if let Some(node) = parent_specialization_node(tcx, impl_def_id) {
87         check_always_applicable(tcx, impl_def_id, node);
88     }
89 }
90
91 fn parent_specialization_node(tcx: TyCtxt<'_>, impl1_def_id: LocalDefId) -> Option<Node> {
92     let trait_ref = tcx.impl_trait_ref(impl1_def_id)?;
93     let trait_def = tcx.trait_def(trait_ref.skip_binder().def_id);
94
95     let impl2_node = trait_def.ancestors(tcx, impl1_def_id.to_def_id()).ok()?.nth(1)?;
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
107 #[instrument(level = "debug", skip(tcx))]
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) {
110         let impl2_def_id = impl2_node.def_id();
111         debug!(?impl2_def_id, ?impl2_substs);
112
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
119         let span = tcx.def_span(impl1_def_id);
120         check_constness(tcx, impl1_def_id, impl2_node, span);
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 /// 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
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 ///
153 /// ```ignore (illustrative)
154 /// impl<A, B> Foo<A> for B { /* impl2 */ }
155 /// impl<C> Foo<Vec<C>> for C { /* impl1 */ }
156 /// ```
157 ///
158 /// Would return `S1 = [C]` and `S2 = [Vec<C>, C]`.
159 fn get_impl_substs(
160     tcx: TyCtxt<'_>,
161     impl1_def_id: LocalDefId,
162     impl2_node: Node,
163 ) -> Option<(SubstsRef<'_>, SubstsRef<'_>)> {
164     let infcx = &tcx.infer_ctxt().build();
165     let ocx = ObligationCtxt::new(infcx);
166     let param_env = tcx.param_env(impl1_def_id);
167
168     let assumed_wf_types =
169         ocx.assumed_wf_types(param_env, tcx.def_span(impl1_def_id), impl1_def_id);
170
171     let impl1_substs = InternalSubsts::identity_for_item(tcx, impl1_def_id.to_def_id());
172     let impl2_substs =
173         translate_substs(infcx, param_env, impl1_def_id.to_def_id(), impl1_substs, impl2_node);
174
175     let errors = ocx.select_all_or_error();
176     if !errors.is_empty() {
177         ocx.infcx.err_ctxt().report_fulfillment_errors(&errors, None);
178         return None;
179     }
180
181     let implied_bounds = infcx.implied_bounds_tys(param_env, impl1_def_id, assumed_wf_types);
182     let outlives_env = OutlivesEnvironment::with_bounds(param_env, Some(infcx), implied_bounds);
183     let _ =
184         infcx.err_ctxt().check_region_obligations_and_report_errors(impl1_def_id, &outlives_env);
185     let Ok(impl2_substs) = infcx.fully_resolve(impl2_substs) else {
186         let span = tcx.def_span(impl1_def_id);
187         tcx.sess.emit_err(SubstsOnOverriddenImpl { span });
188         return None;
189     };
190     Some((impl1_substs, impl2_substs))
191 }
192
193 /// Returns a list of all of the unconstrained subst of the given impl.
194 ///
195 /// For example given the impl:
196 ///
197 /// impl<'a, T, I> ... where &'a I: IntoIterator<Item=&'a T>
198 ///
199 /// This would return the substs corresponding to `['a, I]`, because knowing
200 /// `'a` and `I` determines the value of `T`.
201 fn unconstrained_parent_impl_substs<'tcx>(
202     tcx: TyCtxt<'tcx>,
203     impl_def_id: DefId,
204     impl_substs: SubstsRef<'tcx>,
205 ) -> Vec<GenericArg<'tcx>> {
206     let impl_generic_predicates = tcx.predicates_of(impl_def_id);
207     let mut unconstrained_parameters = FxHashSet::default();
208     let mut constrained_params = FxHashSet::default();
209     let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).map(ty::EarlyBinder::subst_identity);
210
211     // Unfortunately the functions in `constrained_generic_parameters` don't do
212     // what we want here. We want only a list of constrained parameters while
213     // the functions in `cgp` add the constrained parameters to a list of
214     // unconstrained parameters.
215     for (predicate, _) in impl_generic_predicates.predicates.iter() {
216         if let ty::PredicateKind::Clause(ty::Clause::Projection(proj)) =
217             predicate.kind().skip_binder()
218         {
219             let projection_ty = proj.projection_ty;
220             let projected_ty = proj.term;
221
222             let unbound_trait_ref = projection_ty.trait_ref(tcx);
223             if Some(unbound_trait_ref) == impl_trait_ref {
224                 continue;
225             }
226
227             unconstrained_parameters.extend(cgp::parameters_for(&projection_ty, true));
228
229             for param in cgp::parameters_for(&projected_ty, false) {
230                 if !unconstrained_parameters.contains(&param) {
231                     constrained_params.insert(param.0);
232                 }
233             }
234
235             unconstrained_parameters.extend(cgp::parameters_for(&projected_ty, true));
236         }
237     }
238
239     impl_substs
240         .iter()
241         .enumerate()
242         .filter(|&(idx, _)| !constrained_params.contains(&(idx as u32)))
243         .map(|(_, arg)| arg)
244         .collect()
245 }
246
247 /// Check that parameters of the derived impl don't occur more than once in the
248 /// equated substs of the base impl.
249 ///
250 /// For example forbid the following:
251 ///
252 /// ```ignore (illustrative)
253 /// impl<A> Tr for A { }
254 /// impl<B> Tr for (B, B) { }
255 /// ```
256 ///
257 /// Note that only consider the unconstrained parameters of the base impl:
258 ///
259 /// ```ignore (illustrative)
260 /// impl<S, I: IntoIterator<Item = S>> Tr<S> for I { }
261 /// impl<T> Tr<T> for Vec<T> { }
262 /// ```
263 ///
264 /// The substs for the parent impl here are `[T, Vec<T>]`, which repeats `T`,
265 /// but `S` is constrained in the parent impl, so `parent_substs` is only
266 /// `[Vec<T>]`. This means we allow this impl.
267 fn check_duplicate_params<'tcx>(
268     tcx: TyCtxt<'tcx>,
269     impl1_substs: SubstsRef<'tcx>,
270     parent_substs: &Vec<GenericArg<'tcx>>,
271     span: Span,
272 ) {
273     let mut base_params = cgp::parameters_for(parent_substs, true);
274     base_params.sort_by_key(|param| param.0);
275     if let (_, [duplicate, ..]) = base_params.partition_dedup() {
276         let param = impl1_substs[duplicate.0 as usize];
277         tcx.sess
278             .struct_span_err(span, &format!("specializing impl repeats parameter `{}`", param))
279             .emit();
280     }
281 }
282
283 /// Check that `'static` lifetimes are not introduced by the specializing impl.
284 ///
285 /// For example forbid the following:
286 ///
287 /// ```ignore (illustrative)
288 /// impl<A> Tr for A { }
289 /// impl Tr for &'static i32 { }
290 /// ```
291 fn check_static_lifetimes<'tcx>(
292     tcx: TyCtxt<'tcx>,
293     parent_substs: &Vec<GenericArg<'tcx>>,
294     span: Span,
295 ) {
296     if tcx.any_free_region_meets(parent_substs, |r| r.is_static()) {
297         tcx.sess.struct_span_err(span, "cannot specialize on `'static` lifetime").emit();
298     }
299 }
300
301 /// Check whether predicates on the specializing impl (`impl1`) are allowed.
302 ///
303 /// Each predicate `P` must be one of:
304 ///
305 /// * Global (not reference any parameters).
306 /// * A `T: Tr` predicate where `Tr` is an always-applicable trait.
307 /// * Present on the base impl `impl2`.
308 ///     * This check is done using the `trait_predicates_eq` function below.
309 /// * A well-formed predicate of a type argument of the trait being implemented,
310 ///   including the `Self`-type.
311 #[instrument(level = "debug", skip(tcx))]
312 fn check_predicates<'tcx>(
313     tcx: TyCtxt<'tcx>,
314     impl1_def_id: LocalDefId,
315     impl1_substs: SubstsRef<'tcx>,
316     impl2_node: Node,
317     impl2_substs: SubstsRef<'tcx>,
318     span: Span,
319 ) {
320     let instantiated = tcx.predicates_of(impl1_def_id).instantiate(tcx, impl1_substs);
321     let impl1_predicates: Vec<_> = traits::elaborate_predicates_with_span(
322         tcx,
323         std::iter::zip(
324             instantiated.predicates,
325             // Don't drop predicates (unsound!) because `spans` is too short
326             instantiated.spans.into_iter().chain(std::iter::repeat(span)),
327         ),
328     )
329     .map(|obligation| (obligation.predicate, obligation.cause.span))
330     .collect();
331
332     let mut impl2_predicates = if impl2_node.is_from_trait() {
333         // Always applicable traits have to be always applicable without any
334         // assumptions.
335         Vec::new()
336     } else {
337         traits::elaborate_predicates(
338             tcx,
339             tcx.predicates_of(impl2_node.def_id())
340                 .instantiate(tcx, impl2_substs)
341                 .predicates
342                 .into_iter(),
343         )
344         .map(|obligation| obligation.predicate)
345         .collect()
346     };
347     debug!(?impl1_predicates, ?impl2_predicates);
348
349     // Since impls of always applicable traits don't get to assume anything, we
350     // can also assume their supertraits apply.
351     //
352     // For example, we allow:
353     //
354     // #[rustc_specialization_trait]
355     // trait AlwaysApplicable: Debug { }
356     //
357     // impl<T> Tr for T { }
358     // impl<T: AlwaysApplicable> Tr for T { }
359     //
360     // Specializing on `AlwaysApplicable` allows also specializing on `Debug`
361     // which is sound because we forbid impls like the following
362     //
363     // impl<D: Debug> AlwaysApplicable for D { }
364     let always_applicable_traits = impl1_predicates.iter().copied().filter(|&(predicate, _)| {
365         matches!(
366             trait_predicate_kind(tcx, predicate),
367             Some(TraitSpecializationKind::AlwaysApplicable)
368         )
369     });
370
371     // Include the well-formed predicates of the type parameters of the impl.
372     for arg in tcx.impl_trait_ref(impl1_def_id).unwrap().subst_identity().substs {
373         let infcx = &tcx.infer_ctxt().build();
374         let obligations =
375             wf::obligations(infcx, tcx.param_env(impl1_def_id), impl1_def_id, 0, arg, span)
376                 .unwrap();
377
378         assert!(!obligations.needs_infer());
379         impl2_predicates.extend(
380             traits::elaborate_obligations(tcx, obligations).map(|obligation| obligation.predicate),
381         )
382     }
383     impl2_predicates.extend(
384         traits::elaborate_predicates_with_span(tcx, always_applicable_traits)
385             .map(|obligation| obligation.predicate),
386     );
387
388     for (predicate, span) in impl1_predicates {
389         if !impl2_predicates.iter().any(|pred2| trait_predicates_eq(tcx, predicate, *pred2, span)) {
390             check_specialization_on(tcx, predicate, span)
391         }
392     }
393 }
394
395 /// Checks if some predicate on the specializing impl (`predicate1`) is the same
396 /// as some predicate on the base impl (`predicate2`).
397 ///
398 /// This basically just checks syntactic equivalence, but is a little more
399 /// forgiving since we want to equate `T: Tr` with `T: ~const Tr` so this can work:
400 ///
401 /// ```ignore (illustrative)
402 /// #[rustc_specialization_trait]
403 /// trait Specialize { }
404 ///
405 /// impl<T: Bound> Tr for T { }
406 /// impl<T: ~const Bound + Specialize> const Tr for T { }
407 /// ```
408 ///
409 /// However, we *don't* want to allow the reverse, i.e., when the bound on the
410 /// specializing impl is not as const as the bound on the base impl:
411 ///
412 /// ```ignore (illustrative)
413 /// impl<T: ~const Bound> const Tr for T { }
414 /// impl<T: Bound + Specialize> const Tr for T { } // should be T: ~const Bound
415 /// ```
416 ///
417 /// So we make that check in this function and try to raise a helpful error message.
418 fn trait_predicates_eq<'tcx>(
419     tcx: TyCtxt<'tcx>,
420     predicate1: ty::Predicate<'tcx>,
421     predicate2: ty::Predicate<'tcx>,
422     span: Span,
423 ) -> bool {
424     let pred1_kind = predicate1.kind().skip_binder();
425     let pred2_kind = predicate2.kind().skip_binder();
426     let (trait_pred1, trait_pred2) = match (pred1_kind, pred2_kind) {
427         (
428             ty::PredicateKind::Clause(ty::Clause::Trait(pred1)),
429             ty::PredicateKind::Clause(ty::Clause::Trait(pred2)),
430         ) => (pred1, pred2),
431         // Just use plain syntactic equivalence if either of the predicates aren't
432         // trait predicates or have bound vars.
433         _ => return predicate1 == predicate2,
434     };
435
436     let predicates_equal_modulo_constness = {
437         let pred1_unconsted =
438             ty::TraitPredicate { constness: ty::BoundConstness::NotConst, ..trait_pred1 };
439         let pred2_unconsted =
440             ty::TraitPredicate { constness: ty::BoundConstness::NotConst, ..trait_pred2 };
441         pred1_unconsted == pred2_unconsted
442     };
443
444     if !predicates_equal_modulo_constness {
445         return false;
446     }
447
448     // Check that the predicate on the specializing impl is at least as const as
449     // the one on the base.
450     match (trait_pred2.constness, trait_pred1.constness) {
451         (ty::BoundConstness::ConstIfConst, ty::BoundConstness::NotConst) => {
452             tcx.sess.struct_span_err(span, "missing `~const` qualifier for specialization").emit();
453         }
454         _ => {}
455     }
456
457     true
458 }
459
460 #[instrument(level = "debug", skip(tcx))]
461 fn check_specialization_on<'tcx>(tcx: TyCtxt<'tcx>, predicate: ty::Predicate<'tcx>, span: Span) {
462     match predicate.kind().skip_binder() {
463         // Global predicates are either always true or always false, so we
464         // are fine to specialize on.
465         _ if predicate.is_global() => (),
466         // We allow specializing on explicitly marked traits with no associated
467         // items.
468         ty::PredicateKind::Clause(ty::Clause::Trait(ty::TraitPredicate {
469             trait_ref,
470             constness: _,
471             polarity: _,
472         })) => {
473             if !matches!(
474                 trait_predicate_kind(tcx, predicate),
475                 Some(TraitSpecializationKind::Marker)
476             ) {
477                 tcx.sess
478                     .struct_span_err(
479                         span,
480                         &format!(
481                             "cannot specialize on trait `{}`",
482                             tcx.def_path_str(trait_ref.def_id),
483                         ),
484                     )
485                     .emit();
486             }
487         }
488         ty::PredicateKind::Clause(ty::Clause::Projection(ty::ProjectionPredicate {
489             projection_ty,
490             term,
491         })) => {
492             tcx.sess
493                 .struct_span_err(
494                     span,
495                     &format!("cannot specialize on associated type `{projection_ty} == {term}`",),
496                 )
497                 .emit();
498         }
499         _ => {
500             tcx.sess
501                 .struct_span_err(span, &format!("cannot specialize on predicate `{}`", predicate))
502                 .emit();
503         }
504     }
505 }
506
507 fn trait_predicate_kind<'tcx>(
508     tcx: TyCtxt<'tcx>,
509     predicate: ty::Predicate<'tcx>,
510 ) -> Option<TraitSpecializationKind> {
511     match predicate.kind().skip_binder() {
512         ty::PredicateKind::Clause(ty::Clause::Trait(ty::TraitPredicate {
513             trait_ref,
514             constness: _,
515             polarity: _,
516         })) => Some(tcx.trait_def(trait_ref.def_id).specialization_kind),
517         ty::PredicateKind::Clause(ty::Clause::RegionOutlives(_))
518         | ty::PredicateKind::Clause(ty::Clause::TypeOutlives(_))
519         | ty::PredicateKind::Clause(ty::Clause::Projection(_))
520         | ty::PredicateKind::WellFormed(_)
521         | ty::PredicateKind::Subtype(_)
522         | ty::PredicateKind::Coerce(_)
523         | ty::PredicateKind::ObjectSafe(_)
524         | ty::PredicateKind::ClosureKind(..)
525         | ty::PredicateKind::ConstEvaluatable(..)
526         | ty::PredicateKind::ConstEquate(..)
527         | ty::PredicateKind::Ambiguous
528         | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
529     }
530 }