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