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