]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_trait_selection/src/traits/coherence.rs
rustc_trait_selection changes
[rust.git] / compiler / rustc_trait_selection / src / traits / coherence.rs
1 //! See Rustc Dev Guide chapters on [trait-resolution] and [trait-specialization] for more info on
2 //! how this works.
3 //!
4 //! [trait-resolution]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
5 //! [trait-specialization]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
6
7 use crate::infer::outlives::env::OutlivesEnvironment;
8 use crate::infer::{CombinedSnapshot, InferOk, RegionckMode};
9 use crate::traits::select::IntercrateAmbiguityCause;
10 use crate::traits::util::impl_subject_and_oblig;
11 use crate::traits::SkipLeakCheck;
12 use crate::traits::{
13     self, FulfillmentContext, Normalized, Obligation, ObligationCause, PredicateObligation,
14     PredicateObligations, SelectionContext,
15 };
16 //use rustc_data_structures::fx::FxHashMap;
17 use rustc_errors::Diagnostic;
18 use rustc_hir::def_id::{DefId, LOCAL_CRATE};
19 use rustc_hir::CRATE_HIR_ID;
20 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
21 use rustc_infer::traits::{util, TraitEngine};
22 use rustc_middle::traits::specialization_graph::OverlapMode;
23 use rustc_middle::ty::fast_reject::{self, TreatParams};
24 use rustc_middle::ty::fold::TypeFoldable;
25 use rustc_middle::ty::subst::Subst;
26 use rustc_middle::ty::{self, ImplSubject, Ty, TyCtxt};
27 use rustc_span::symbol::sym;
28 use rustc_span::DUMMY_SP;
29 use std::fmt::Debug;
30 use std::iter;
31
32 /// Whether we do the orphan check relative to this crate or
33 /// to some remote crate.
34 #[derive(Copy, Clone, Debug)]
35 enum InCrate {
36     Local,
37     Remote,
38 }
39
40 #[derive(Debug, Copy, Clone)]
41 pub enum Conflict {
42     Upstream,
43     Downstream,
44 }
45
46 pub struct OverlapResult<'tcx> {
47     pub impl_header: ty::ImplHeader<'tcx>,
48     pub intercrate_ambiguity_causes: Vec<IntercrateAmbiguityCause>,
49
50     /// `true` if the overlap might've been permitted before the shift
51     /// to universes.
52     pub involves_placeholder: bool,
53 }
54
55 pub fn add_placeholder_note(err: &mut Diagnostic) {
56     err.note(
57         "this behavior recently changed as a result of a bug fix; \
58          see rust-lang/rust#56105 for details",
59     );
60 }
61
62 /// If there are types that satisfy both impls, invokes `on_overlap`
63 /// with a suitably-freshened `ImplHeader` with those types
64 /// substituted. Otherwise, invokes `no_overlap`.
65 #[instrument(skip(tcx, skip_leak_check, on_overlap, no_overlap), level = "debug")]
66 pub fn overlapping_impls<F1, F2, R>(
67     tcx: TyCtxt<'_>,
68     impl1_def_id: DefId,
69     impl2_def_id: DefId,
70     skip_leak_check: SkipLeakCheck,
71     overlap_mode: OverlapMode,
72     on_overlap: F1,
73     no_overlap: F2,
74 ) -> R
75 where
76     F1: FnOnce(OverlapResult<'_>) -> R,
77     F2: FnOnce() -> R,
78 {
79     // Before doing expensive operations like entering an inference context, do
80     // a quick check via fast_reject to tell if the impl headers could possibly
81     // unify.
82     let impl1_ref = tcx.impl_trait_ref(impl1_def_id);
83     let impl2_ref = tcx.impl_trait_ref(impl2_def_id);
84
85     // Check if any of the input types definitely do not unify.
86     if iter::zip(
87         impl1_ref.iter().flat_map(|tref| tref.substs.types()),
88         impl2_ref.iter().flat_map(|tref| tref.substs.types()),
89     )
90     .any(|(ty1, ty2)| {
91         let t1 = fast_reject::simplify_type(tcx, ty1, TreatParams::AsPlaceholders);
92         let t2 = fast_reject::simplify_type(tcx, ty2, TreatParams::AsPlaceholders);
93
94         if let (Some(t1), Some(t2)) = (t1, t2) {
95             // Simplified successfully
96             t1 != t2
97         } else {
98             // Types might unify
99             false
100         }
101     }) {
102         // Some types involved are definitely different, so the impls couldn't possibly overlap.
103         debug!("overlapping_impls: fast_reject early-exit");
104         return no_overlap();
105     }
106
107     let overlaps = tcx.infer_ctxt().enter(|infcx| {
108         let selcx = &mut SelectionContext::intercrate(&infcx);
109         overlap(selcx, skip_leak_check, impl1_def_id, impl2_def_id, overlap_mode).is_some()
110     });
111
112     if !overlaps {
113         return no_overlap();
114     }
115
116     // In the case where we detect an error, run the check again, but
117     // this time tracking intercrate ambiguity causes for better
118     // diagnostics. (These take time and can lead to false errors.)
119     tcx.infer_ctxt().enter(|infcx| {
120         let selcx = &mut SelectionContext::intercrate(&infcx);
121         selcx.enable_tracking_intercrate_ambiguity_causes();
122         on_overlap(
123             overlap(selcx, skip_leak_check, impl1_def_id, impl2_def_id, overlap_mode).unwrap(),
124         )
125     })
126 }
127
128 fn with_fresh_ty_vars<'cx, 'tcx>(
129     selcx: &mut SelectionContext<'cx, 'tcx>,
130     param_env: ty::ParamEnv<'tcx>,
131     impl_def_id: DefId,
132 ) -> ty::ImplHeader<'tcx> {
133     let tcx = selcx.tcx();
134     let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
135
136     let header = ty::ImplHeader {
137         impl_def_id,
138         self_ty: tcx.type_of(impl_def_id).subst(tcx, impl_substs),
139         trait_ref: tcx.impl_trait_ref(impl_def_id).subst(tcx, impl_substs),
140         predicates: tcx.predicates_of(impl_def_id).instantiate(tcx, impl_substs).predicates,
141     };
142
143     let Normalized { value: mut header, obligations } =
144         traits::normalize(selcx, param_env, ObligationCause::dummy(), header);
145
146     header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
147     header
148 }
149
150 /// Can both impl `a` and impl `b` be satisfied by a common type (including
151 /// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
152 fn overlap<'cx, 'tcx>(
153     selcx: &mut SelectionContext<'cx, 'tcx>,
154     skip_leak_check: SkipLeakCheck,
155     impl1_def_id: DefId,
156     impl2_def_id: DefId,
157     overlap_mode: OverlapMode,
158 ) -> Option<OverlapResult<'tcx>> {
159     debug!(
160         "overlap(impl1_def_id={:?}, impl2_def_id={:?}, overlap_mode={:?})",
161         impl1_def_id, impl2_def_id, overlap_mode
162     );
163
164     selcx.infcx().probe_maybe_skip_leak_check(skip_leak_check.is_yes(), |snapshot| {
165         overlap_within_probe(selcx, impl1_def_id, impl2_def_id, overlap_mode, snapshot)
166     })
167 }
168
169 fn overlap_within_probe<'cx, 'tcx>(
170     selcx: &mut SelectionContext<'cx, 'tcx>,
171     impl1_def_id: DefId,
172     impl2_def_id: DefId,
173     overlap_mode: OverlapMode,
174     snapshot: &CombinedSnapshot<'_, 'tcx>,
175 ) -> Option<OverlapResult<'tcx>> {
176     let infcx = selcx.infcx();
177
178     if overlap_mode.use_negative_impl() {
179         if negative_impl(selcx, impl1_def_id, impl2_def_id)
180             || negative_impl(selcx, impl2_def_id, impl1_def_id)
181         {
182             return None;
183         }
184     }
185
186     // For the purposes of this check, we don't bring any placeholder
187     // types into scope; instead, we replace the generic types with
188     // fresh type variables, and hence we do our evaluations in an
189     // empty environment.
190     let param_env = ty::ParamEnv::empty();
191
192     let impl1_header = with_fresh_ty_vars(selcx, param_env, impl1_def_id);
193     let impl2_header = with_fresh_ty_vars(selcx, param_env, impl2_def_id);
194
195     let obligations = equate_impl_headers(selcx, &impl1_header, &impl2_header)?;
196     debug!("overlap: unification check succeeded");
197
198     if overlap_mode.use_implicit_negative() {
199         if implicit_negative(selcx, param_env, &impl1_header, impl2_header, obligations) {
200             return None;
201         }
202     }
203
204     // We disable the leak when when creating the `snapshot` by using
205     // `infcx.probe_maybe_disable_leak_check`.
206     if infcx.leak_check(true, snapshot).is_err() {
207         debug!("overlap: leak check failed");
208         return None;
209     }
210
211     let intercrate_ambiguity_causes = selcx.take_intercrate_ambiguity_causes();
212     debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
213
214     let involves_placeholder =
215         matches!(selcx.infcx().region_constraints_added_in_snapshot(snapshot), Some(true));
216
217     let impl_header = selcx.infcx().resolve_vars_if_possible(impl1_header);
218     Some(OverlapResult { impl_header, intercrate_ambiguity_causes, involves_placeholder })
219 }
220
221 fn equate_impl_headers<'cx, 'tcx>(
222     selcx: &mut SelectionContext<'cx, 'tcx>,
223     impl1_header: &ty::ImplHeader<'tcx>,
224     impl2_header: &ty::ImplHeader<'tcx>,
225 ) -> Option<PredicateObligations<'tcx>> {
226     // Do `a` and `b` unify? If not, no overlap.
227     debug!("equate_impl_headers(impl1_header={:?}, impl2_header={:?}", impl1_header, impl2_header);
228     selcx
229         .infcx()
230         .at(&ObligationCause::dummy(), ty::ParamEnv::empty())
231         .eq_impl_headers(impl1_header, impl2_header)
232         .map(|infer_ok| infer_ok.obligations)
233         .ok()
234 }
235
236 /// Given impl1 and impl2 check if both impls can be satisfied by a common type (including
237 /// where-clauses) If so, return false, otherwise return true, they are disjoint.
238 fn implicit_negative<'cx, 'tcx>(
239     selcx: &mut SelectionContext<'cx, 'tcx>,
240     param_env: ty::ParamEnv<'tcx>,
241     impl1_header: &ty::ImplHeader<'tcx>,
242     impl2_header: ty::ImplHeader<'tcx>,
243     obligations: PredicateObligations<'tcx>,
244 ) -> bool {
245     // There's no overlap if obligations are unsatisfiable or if the obligation negated is
246     // satisfied.
247     //
248     // For example, given these two impl headers:
249     //
250     // `impl<'a> From<&'a str> for Box<dyn Error>`
251     // `impl<E> From<E> for Box<dyn Error> where E: Error`
252     //
253     // So we have:
254     //
255     // `Box<dyn Error>: From<&'?a str>`
256     // `Box<dyn Error>: From<?E>`
257     //
258     // After equating the two headers:
259     //
260     // `Box<dyn Error> = Box<dyn Error>`
261     // So, `?E = &'?a str` and then given the where clause `&'?a str: Error`.
262     //
263     // If the obligation `&'?a str: Error` holds, it means that there's overlap. If that doesn't
264     // hold we need to check if `&'?a str: !Error` holds, if doesn't hold there's overlap because
265     // at some point an impl for `&'?a str: Error` could be added.
266     debug!(
267         "implicit_negative(impl1_header={:?}, impl2_header={:?}, obligations={:?})",
268         impl1_header, impl2_header, obligations
269     );
270     let infcx = selcx.infcx();
271     let opt_failing_obligation = impl1_header
272         .predicates
273         .iter()
274         .copied()
275         .chain(impl2_header.predicates)
276         .map(|p| infcx.resolve_vars_if_possible(p))
277         .map(|p| Obligation {
278             cause: ObligationCause::dummy(),
279             param_env,
280             recursion_depth: 0,
281             predicate: p,
282         })
283         .chain(obligations)
284         .find(|o| !selcx.predicate_may_hold_fatal(o));
285
286     if let Some(failing_obligation) = opt_failing_obligation {
287         debug!("overlap: obligation unsatisfiable {:?}", failing_obligation);
288         true
289     } else {
290         false
291     }
292 }
293
294 /// Given impl1 and impl2 check if both impls are never satisfied by a common type (including
295 /// where-clauses) If so, return true, they are disjoint and false otherwise.
296 fn negative_impl<'cx, 'tcx>(
297     selcx: &mut SelectionContext<'cx, 'tcx>,
298     impl1_def_id: DefId,
299     impl2_def_id: DefId,
300 ) -> bool {
301     debug!("negative_impl(impl1_def_id={:?}, impl2_def_id={:?})", impl1_def_id, impl2_def_id);
302     let tcx = selcx.infcx().tcx;
303
304     // Create an infcx, taking the predicates of impl1 as assumptions:
305     tcx.infer_ctxt().enter(|infcx| {
306         // create a parameter environment corresponding to a (placeholder) instantiation of impl1
307         let impl_env = tcx.param_env(impl1_def_id);
308         let subject1 = match traits::fully_normalize(
309             &infcx,
310             FulfillmentContext::new(),
311             ObligationCause::dummy(),
312             impl_env,
313             tcx.impl_subject(impl1_def_id),
314         ) {
315             Ok(s) => s,
316             Err(err) => bug!("failed to fully normalize {:?}: {:?}", impl1_def_id, err),
317         };
318
319         // Attempt to prove that impl2 applies, given all of the above.
320         let selcx = &mut SelectionContext::new(&infcx);
321         let impl2_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl2_def_id);
322         let (subject2, obligations) =
323             impl_subject_and_oblig(selcx, impl_env, impl2_def_id, impl2_substs);
324
325         !equate(&infcx, impl_env, impl1_def_id, subject1, subject2, obligations)
326     })
327 }
328
329 fn equate<'cx, 'tcx>(
330     infcx: &InferCtxt<'cx, 'tcx>,
331     impl_env: ty::ParamEnv<'tcx>,
332     impl1_def_id: DefId,
333     subject1: ImplSubject<'tcx>,
334     subject2: ImplSubject<'tcx>,
335     obligations: impl Iterator<Item = PredicateObligation<'tcx>>,
336 ) -> bool {
337     // do the impls unify? If not, not disjoint.
338     let Ok(InferOk { obligations: more_obligations, .. }) =
339         infcx.at(&ObligationCause::dummy(), impl_env).eq(subject1, subject2)
340     else {
341         debug!("explicit_disjoint: {:?} does not unify with {:?}", subject1, subject2);
342         return true;
343     };
344
345     let selcx = &mut SelectionContext::new(&infcx);
346     let opt_failing_obligation = obligations
347         .into_iter()
348         .chain(more_obligations)
349         .find(|o| negative_impl_exists(selcx, impl_env, impl1_def_id, o));
350
351     if let Some(failing_obligation) = opt_failing_obligation {
352         debug!("overlap: obligation unsatisfiable {:?}", failing_obligation);
353         false
354     } else {
355         true
356     }
357 }
358
359 /// Try to prove that a negative impl exist for the given obligation and its super predicates.
360 #[instrument(level = "debug", skip(selcx))]
361 fn negative_impl_exists<'cx, 'tcx>(
362     selcx: &SelectionContext<'cx, 'tcx>,
363     param_env: ty::ParamEnv<'tcx>,
364     region_context: DefId,
365     o: &PredicateObligation<'tcx>,
366 ) -> bool {
367     let infcx = &selcx.infcx().fork();
368
369     if resolve_negative_obligation(infcx, param_env, region_context, o) {
370         return true;
371     }
372
373     // Try to prove a negative obligation exists for super predicates
374     for o in util::elaborate_predicates(infcx.tcx, iter::once(o.predicate)) {
375         if resolve_negative_obligation(infcx, param_env, region_context, &o) {
376             return true;
377         }
378     }
379
380     false
381 }
382
383 #[instrument(level = "debug", skip(infcx))]
384 fn resolve_negative_obligation<'cx, 'tcx>(
385     infcx: &InferCtxt<'cx, 'tcx>,
386     param_env: ty::ParamEnv<'tcx>,
387     region_context: DefId,
388     o: &PredicateObligation<'tcx>,
389 ) -> bool {
390     let tcx = infcx.tcx;
391
392     let Some(o) = o.flip_polarity(tcx) else {
393         return false;
394     };
395
396     let mut fulfillment_cx = FulfillmentContext::new();
397     fulfillment_cx.register_predicate_obligation(infcx, o);
398
399     let errors = fulfillment_cx.select_all_or_error(infcx);
400
401     if !errors.is_empty() {
402         return false;
403     }
404
405     let mut outlives_env = OutlivesEnvironment::new(param_env);
406     // FIXME -- add "assumed to be well formed" types into the `outlives_env`
407
408     // "Save" the accumulated implied bounds into the outlives environment
409     // (due to the FIXME above, there aren't any, but this step is still needed).
410     // The "body id" is given as `CRATE_HIR_ID`, which is the same body-id used
411     // by the "dummy" causes elsewhere (body-id is only relevant when checking
412     // function bodies with closures).
413     outlives_env.save_implied_bounds(CRATE_HIR_ID);
414
415     infcx.process_registered_region_obligations(
416         outlives_env.region_bound_pairs_map(),
417         Some(tcx.lifetimes.re_root_empty),
418         param_env,
419     );
420
421     let errors = infcx.resolve_regions(region_context, &outlives_env, RegionckMode::default());
422
423     if !errors.is_empty() {
424         return false;
425     }
426
427     true
428 }
429
430 pub fn trait_ref_is_knowable<'tcx>(
431     tcx: TyCtxt<'tcx>,
432     trait_ref: ty::TraitRef<'tcx>,
433 ) -> Option<Conflict> {
434     debug!("trait_ref_is_knowable(trait_ref={:?})", trait_ref);
435     if orphan_check_trait_ref(tcx, trait_ref, InCrate::Remote).is_ok() {
436         // A downstream or cousin crate is allowed to implement some
437         // substitution of this trait-ref.
438         return Some(Conflict::Downstream);
439     }
440
441     if trait_ref_is_local_or_fundamental(tcx, trait_ref) {
442         // This is a local or fundamental trait, so future-compatibility
443         // is no concern. We know that downstream/cousin crates are not
444         // allowed to implement a substitution of this trait ref, which
445         // means impls could only come from dependencies of this crate,
446         // which we already know about.
447         return None;
448     }
449
450     // This is a remote non-fundamental trait, so if another crate
451     // can be the "final owner" of a substitution of this trait-ref,
452     // they are allowed to implement it future-compatibly.
453     //
454     // However, if we are a final owner, then nobody else can be,
455     // and if we are an intermediate owner, then we don't care
456     // about future-compatibility, which means that we're OK if
457     // we are an owner.
458     if orphan_check_trait_ref(tcx, trait_ref, InCrate::Local).is_ok() {
459         debug!("trait_ref_is_knowable: orphan check passed");
460         None
461     } else {
462         debug!("trait_ref_is_knowable: nonlocal, nonfundamental, unowned");
463         Some(Conflict::Upstream)
464     }
465 }
466
467 pub fn trait_ref_is_local_or_fundamental<'tcx>(
468     tcx: TyCtxt<'tcx>,
469     trait_ref: ty::TraitRef<'tcx>,
470 ) -> bool {
471     trait_ref.def_id.krate == LOCAL_CRATE || tcx.has_attr(trait_ref.def_id, sym::fundamental)
472 }
473
474 pub enum OrphanCheckErr<'tcx> {
475     NonLocalInputType(Vec<(Ty<'tcx>, bool /* Is this the first input type? */)>),
476     UncoveredTy(Ty<'tcx>, Option<Ty<'tcx>>),
477 }
478
479 /// Checks the coherence orphan rules. `impl_def_id` should be the
480 /// `DefId` of a trait impl. To pass, either the trait must be local, or else
481 /// two conditions must be satisfied:
482 ///
483 /// 1. All type parameters in `Self` must be "covered" by some local type constructor.
484 /// 2. Some local type must appear in `Self`.
485 pub fn orphan_check(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Result<(), OrphanCheckErr<'_>> {
486     debug!("orphan_check({:?})", impl_def_id);
487
488     // We only except this routine to be invoked on implementations
489     // of a trait, not inherent implementations.
490     let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
491     debug!("orphan_check: trait_ref={:?}", trait_ref);
492
493     // If the *trait* is local to the crate, ok.
494     if trait_ref.def_id.is_local() {
495         debug!("trait {:?} is local to current crate", trait_ref.def_id);
496         return Ok(());
497     }
498
499     orphan_check_trait_ref(tcx, trait_ref, InCrate::Local)
500 }
501
502 /// Checks whether a trait-ref is potentially implementable by a crate.
503 ///
504 /// The current rule is that a trait-ref orphan checks in a crate C:
505 ///
506 /// 1. Order the parameters in the trait-ref in subst order - Self first,
507 ///    others linearly (e.g., `<U as Foo<V, W>>` is U < V < W).
508 /// 2. Of these type parameters, there is at least one type parameter
509 ///    in which, walking the type as a tree, you can reach a type local
510 ///    to C where all types in-between are fundamental types. Call the
511 ///    first such parameter the "local key parameter".
512 ///     - e.g., `Box<LocalType>` is OK, because you can visit LocalType
513 ///       going through `Box`, which is fundamental.
514 ///     - similarly, `FundamentalPair<Vec<()>, Box<LocalType>>` is OK for
515 ///       the same reason.
516 ///     - but (knowing that `Vec<T>` is non-fundamental, and assuming it's
517 ///       not local), `Vec<LocalType>` is bad, because `Vec<->` is between
518 ///       the local type and the type parameter.
519 /// 3. Before this local type, no generic type parameter of the impl must
520 ///    be reachable through fundamental types.
521 ///     - e.g. `impl<T> Trait<LocalType> for Vec<T>` is fine, as `Vec` is not fundamental.
522 ///     - while `impl<T> Trait<LocalType for Box<T>` results in an error, as `T` is
523 ///       reachable through the fundamental type `Box`.
524 /// 4. Every type in the local key parameter not known in C, going
525 ///    through the parameter's type tree, must appear only as a subtree of
526 ///    a type local to C, with only fundamental types between the type
527 ///    local to C and the local key parameter.
528 ///     - e.g., `Vec<LocalType<T>>>` (or equivalently `Box<Vec<LocalType<T>>>`)
529 ///     is bad, because the only local type with `T` as a subtree is
530 ///     `LocalType<T>`, and `Vec<->` is between it and the type parameter.
531 ///     - similarly, `FundamentalPair<LocalType<T>, T>` is bad, because
532 ///     the second occurrence of `T` is not a subtree of *any* local type.
533 ///     - however, `LocalType<Vec<T>>` is OK, because `T` is a subtree of
534 ///     `LocalType<Vec<T>>`, which is local and has no types between it and
535 ///     the type parameter.
536 ///
537 /// The orphan rules actually serve several different purposes:
538 ///
539 /// 1. They enable link-safety - i.e., 2 mutually-unknowing crates (where
540 ///    every type local to one crate is unknown in the other) can't implement
541 ///    the same trait-ref. This follows because it can be seen that no such
542 ///    type can orphan-check in 2 such crates.
543 ///
544 ///    To check that a local impl follows the orphan rules, we check it in
545 ///    InCrate::Local mode, using type parameters for the "generic" types.
546 ///
547 /// 2. They ground negative reasoning for coherence. If a user wants to
548 ///    write both a conditional blanket impl and a specific impl, we need to
549 ///    make sure they do not overlap. For example, if we write
550 ///    ```
551 ///    impl<T> IntoIterator for Vec<T>
552 ///    impl<T: Iterator> IntoIterator for T
553 ///    ```
554 ///    We need to be able to prove that `Vec<$0>: !Iterator` for every type $0.
555 ///    We can observe that this holds in the current crate, but we need to make
556 ///    sure this will also hold in all unknown crates (both "independent" crates,
557 ///    which we need for link-safety, and also child crates, because we don't want
558 ///    child crates to get error for impl conflicts in a *dependency*).
559 ///
560 ///    For that, we only allow negative reasoning if, for every assignment to the
561 ///    inference variables, every unknown crate would get an orphan error if they
562 ///    try to implement this trait-ref. To check for this, we use InCrate::Remote
563 ///    mode. That is sound because we already know all the impls from known crates.
564 ///
565 /// 3. For non-`#[fundamental]` traits, they guarantee that parent crates can
566 ///    add "non-blanket" impls without breaking negative reasoning in dependent
567 ///    crates. This is the "rebalancing coherence" (RFC 1023) restriction.
568 ///
569 ///    For that, we only a allow crate to perform negative reasoning on
570 ///    non-local-non-`#[fundamental]` only if there's a local key parameter as per (2).
571 ///
572 ///    Because we never perform negative reasoning generically (coherence does
573 ///    not involve type parameters), this can be interpreted as doing the full
574 ///    orphan check (using InCrate::Local mode), substituting non-local known
575 ///    types for all inference variables.
576 ///
577 ///    This allows for crates to future-compatibly add impls as long as they
578 ///    can't apply to types with a key parameter in a child crate - applying
579 ///    the rules, this basically means that every type parameter in the impl
580 ///    must appear behind a non-fundamental type (because this is not a
581 ///    type-system requirement, crate owners might also go for "semantic
582 ///    future-compatibility" involving things such as sealed traits, but
583 ///    the above requirement is sufficient, and is necessary in "open world"
584 ///    cases).
585 ///
586 /// Note that this function is never called for types that have both type
587 /// parameters and inference variables.
588 fn orphan_check_trait_ref<'tcx>(
589     tcx: TyCtxt<'tcx>,
590     trait_ref: ty::TraitRef<'tcx>,
591     in_crate: InCrate,
592 ) -> Result<(), OrphanCheckErr<'tcx>> {
593     debug!("orphan_check_trait_ref(trait_ref={:?}, in_crate={:?})", trait_ref, in_crate);
594
595     if trait_ref.needs_infer() && trait_ref.needs_subst() {
596         bug!(
597             "can't orphan check a trait ref with both params and inference variables {:?}",
598             trait_ref
599         );
600     }
601
602     // Given impl<P1..=Pn> Trait<T1..=Tn> for T0, an impl is valid only
603     // if at least one of the following is true:
604     //
605     // - Trait is a local trait
606     // (already checked in orphan_check prior to calling this function)
607     // - All of
608     //     - At least one of the types T0..=Tn must be a local type.
609     //      Let Ti be the first such type.
610     //     - No uncovered type parameters P1..=Pn may appear in T0..Ti (excluding Ti)
611     //
612     fn uncover_fundamental_ty<'tcx>(
613         tcx: TyCtxt<'tcx>,
614         ty: Ty<'tcx>,
615         in_crate: InCrate,
616     ) -> Vec<Ty<'tcx>> {
617         // FIXME: this is currently somewhat overly complicated,
618         // but fixing this requires a more complicated refactor.
619         if !contained_non_local_types(tcx, ty, in_crate).is_empty() {
620             if let Some(inner_tys) = fundamental_ty_inner_tys(tcx, ty) {
621                 return inner_tys
622                     .flat_map(|ty| uncover_fundamental_ty(tcx, ty, in_crate))
623                     .collect();
624             }
625         }
626
627         vec![ty]
628     }
629
630     let mut non_local_spans = vec![];
631     for (i, input_ty) in trait_ref
632         .substs
633         .types()
634         .flat_map(|ty| uncover_fundamental_ty(tcx, ty, in_crate))
635         .enumerate()
636     {
637         debug!("orphan_check_trait_ref: check ty `{:?}`", input_ty);
638         let non_local_tys = contained_non_local_types(tcx, input_ty, in_crate);
639         if non_local_tys.is_empty() {
640             debug!("orphan_check_trait_ref: ty_is_local `{:?}`", input_ty);
641             return Ok(());
642         } else if let ty::Param(_) = input_ty.kind() {
643             debug!("orphan_check_trait_ref: uncovered ty: `{:?}`", input_ty);
644             let local_type = trait_ref
645                 .substs
646                 .types()
647                 .flat_map(|ty| uncover_fundamental_ty(tcx, ty, in_crate))
648                 .find(|ty| ty_is_local_constructor(*ty, in_crate));
649
650             debug!("orphan_check_trait_ref: uncovered ty local_type: `{:?}`", local_type);
651
652             return Err(OrphanCheckErr::UncoveredTy(input_ty, local_type));
653         }
654
655         non_local_spans.extend(non_local_tys.into_iter().map(|input_ty| (input_ty, i == 0)));
656     }
657     // If we exit above loop, never found a local type.
658     debug!("orphan_check_trait_ref: no local type");
659     Err(OrphanCheckErr::NonLocalInputType(non_local_spans))
660 }
661
662 /// Returns a list of relevant non-local types for `ty`.
663 ///
664 /// This is just `ty` itself unless `ty` is `#[fundamental]`,
665 /// in which case we recursively look into this type.
666 ///
667 /// If `ty` is local itself, this method returns an empty `Vec`.
668 ///
669 /// # Examples
670 ///
671 /// - `u32` is not local, so this returns `[u32]`.
672 /// - for `Foo<u32>`, where `Foo` is a local type, this returns `[]`.
673 /// - `&mut u32` returns `[u32]`, as `&mut` is a fundamental type, similar to `Box`.
674 /// - `Box<Foo<u32>>` returns `[]`, as `Box` is a fundamental type and `Foo` is local.
675 fn contained_non_local_types<'tcx>(
676     tcx: TyCtxt<'tcx>,
677     ty: Ty<'tcx>,
678     in_crate: InCrate,
679 ) -> Vec<Ty<'tcx>> {
680     if ty_is_local_constructor(ty, in_crate) {
681         Vec::new()
682     } else {
683         match fundamental_ty_inner_tys(tcx, ty) {
684             Some(inner_tys) => {
685                 inner_tys.flat_map(|ty| contained_non_local_types(tcx, ty, in_crate)).collect()
686             }
687             None => vec![ty],
688         }
689     }
690 }
691
692 /// For `#[fundamental]` ADTs and `&T` / `&mut T`, returns `Some` with the
693 /// type parameters of the ADT, or `T`, respectively. For non-fundamental
694 /// types, returns `None`.
695 fn fundamental_ty_inner_tys<'tcx>(
696     tcx: TyCtxt<'tcx>,
697     ty: Ty<'tcx>,
698 ) -> Option<impl Iterator<Item = Ty<'tcx>>> {
699     let (first_ty, rest_tys) = match *ty.kind() {
700         ty::Ref(_, ty, _) => (ty, ty::subst::InternalSubsts::empty().types()),
701         ty::Adt(def, substs) if def.is_fundamental() => {
702             let mut types = substs.types();
703
704             // FIXME(eddyb) actually validate `#[fundamental]` up-front.
705             match types.next() {
706                 None => {
707                     tcx.sess.span_err(
708                         tcx.def_span(def.did()),
709                         "`#[fundamental]` requires at least one type parameter",
710                     );
711
712                     return None;
713                 }
714
715                 Some(first_ty) => (first_ty, types),
716             }
717         }
718         _ => return None,
719     };
720
721     Some(iter::once(first_ty).chain(rest_tys))
722 }
723
724 fn def_id_is_local(def_id: DefId, in_crate: InCrate) -> bool {
725     match in_crate {
726         // The type is local to *this* crate - it will not be
727         // local in any other crate.
728         InCrate::Remote => false,
729         InCrate::Local => def_id.is_local(),
730     }
731 }
732
733 fn ty_is_local_constructor(ty: Ty<'_>, in_crate: InCrate) -> bool {
734     debug!("ty_is_local_constructor({:?})", ty);
735
736     match *ty.kind() {
737         ty::Bool
738         | ty::Char
739         | ty::Int(..)
740         | ty::Uint(..)
741         | ty::Float(..)
742         | ty::Str
743         | ty::FnDef(..)
744         | ty::FnPtr(_)
745         | ty::Array(..)
746         | ty::Slice(..)
747         | ty::RawPtr(..)
748         | ty::Ref(..)
749         | ty::Never
750         | ty::Tuple(..)
751         | ty::Param(..)
752         | ty::Projection(..) => false,
753
754         ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) => match in_crate {
755             InCrate::Local => false,
756             // The inference variable might be unified with a local
757             // type in that remote crate.
758             InCrate::Remote => true,
759         },
760
761         ty::Adt(def, _) => def_id_is_local(def.did(), in_crate),
762         ty::Foreign(did) => def_id_is_local(did, in_crate),
763         ty::Opaque(..) => {
764             // This merits some explanation.
765             // Normally, opaque types are not involved when performing
766             // coherence checking, since it is illegal to directly
767             // implement a trait on an opaque type. However, we might
768             // end up looking at an opaque type during coherence checking
769             // if an opaque type gets used within another type (e.g. as
770             // a type parameter). This requires us to decide whether or
771             // not an opaque type should be considered 'local' or not.
772             //
773             // We choose to treat all opaque types as non-local, even
774             // those that appear within the same crate. This seems
775             // somewhat surprising at first, but makes sense when
776             // you consider that opaque types are supposed to hide
777             // the underlying type *within the same crate*. When an
778             // opaque type is used from outside the module
779             // where it is declared, it should be impossible to observe
780             // anything about it other than the traits that it implements.
781             //
782             // The alternative would be to look at the underlying type
783             // to determine whether or not the opaque type itself should
784             // be considered local. However, this could make it a breaking change
785             // to switch the underlying ('defining') type from a local type
786             // to a remote type. This would violate the rule that opaque
787             // types should be completely opaque apart from the traits
788             // that they implement, so we don't use this behavior.
789             false
790         }
791
792         ty::Closure(..) => {
793             // Similar to the `Opaque` case (#83613).
794             false
795         }
796
797         ty::Dynamic(ref tt, ..) => {
798             if let Some(principal) = tt.principal() {
799                 def_id_is_local(principal.def_id(), in_crate)
800             } else {
801                 false
802             }
803         }
804
805         ty::Error(_) => true,
806
807         ty::Generator(..) | ty::GeneratorWitness(..) => {
808             bug!("ty_is_local invoked on unexpected type: {:?}", ty)
809         }
810     }
811 }