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