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