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