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