2020-03-06 11:17:12 -03:00
|
|
|
//! See Rustc Dev Guide chapters on [trait-resolution] and [trait-specialization] for more info on
|
|
|
|
//! how this works.
|
2018-02-25 15:24:14 -06:00
|
|
|
//!
|
2020-03-09 18:33:04 -03:00
|
|
|
//! [trait-resolution]: https://rustc-dev-guide.rust-lang.org/traits/resolution.html
|
|
|
|
//! [trait-specialization]: https://rustc-dev-guide.rust-lang.org/traits/specialization.html
|
2014-09-12 10:54:08 -04:00
|
|
|
|
2022-02-02 14:36:45 -03:00
|
|
|
use crate::infer::outlives::env::OutlivesEnvironment;
|
|
|
|
use crate::infer::{CombinedSnapshot, InferOk, RegionckMode};
|
2019-02-05 11:20:45 -06:00
|
|
|
use crate::traits::select::IntercrateAmbiguityCause;
|
2022-03-24 17:47:10 -03:00
|
|
|
use crate::traits::util::{impl_trait_ref_and_oblig, inherent_impl_and_oblig};
|
2020-01-24 15:57:01 -05:00
|
|
|
use crate::traits::SkipLeakCheck;
|
2021-10-23 00:03:33 -03:00
|
|
|
use crate::traits::{
|
2022-01-21 12:53:50 -03:00
|
|
|
self, FulfillmentContext, Normalized, Obligation, ObligationCause, PredicateObligation,
|
2022-01-22 18:16:11 -03:00
|
|
|
PredicateObligations, SelectionContext,
|
2021-10-23 00:03:33 -03:00
|
|
|
};
|
2022-02-02 14:36:45 -03:00
|
|
|
//use rustc_data_structures::fx::FxHashMap;
|
2022-01-23 20:41:46 +00:00
|
|
|
use rustc_errors::Diagnostic;
|
2020-03-29 17:19:48 +02:00
|
|
|
use rustc_hir::def_id::{DefId, LOCAL_CRATE};
|
2022-02-02 14:36:45 -03:00
|
|
|
use rustc_hir::CRATE_HIR_ID;
|
2022-03-17 12:09:00 -03:00
|
|
|
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
|
2022-03-17 11:26:45 -03:00
|
|
|
use rustc_infer::traits::{util, TraitEngine};
|
2022-01-30 18:55:22 -03:00
|
|
|
use rustc_middle::traits::specialization_graph::OverlapMode;
|
2022-02-21 13:44:55 +01:00
|
|
|
use rustc_middle::ty::fast_reject::{self, TreatParams};
|
2020-03-29 16:41:09 +02:00
|
|
|
use rustc_middle::ty::fold::TypeFoldable;
|
|
|
|
use rustc_middle::ty::subst::Subst;
|
2022-03-20 00:12:03 -03:00
|
|
|
use rustc_middle::ty::{self, ImplSubject, Ty, TyCtxt};
|
2020-01-01 19:30:57 +01:00
|
|
|
use rustc_span::symbol::sym;
|
2019-12-31 20:15:40 +03:00
|
|
|
use rustc_span::DUMMY_SP;
|
2022-03-18 14:07:22 -03:00
|
|
|
use std::fmt::Debug;
|
2020-03-20 05:28:17 +02:00
|
|
|
use std::iter;
|
2014-09-12 10:54:08 -04:00
|
|
|
|
2017-11-22 23:01:51 +02:00
|
|
|
/// Whether we do the orphan check relative to this crate or
|
|
|
|
/// to some remote crate.
|
2017-11-29 20:50:26 +02:00
|
|
|
#[derive(Copy, Clone, Debug)]
|
2017-11-22 23:01:51 +02:00
|
|
|
enum InCrate {
|
|
|
|
Local,
|
2019-12-22 17:42:04 -05:00
|
|
|
Remote,
|
2017-11-22 22:39:40 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Copy, Clone)]
|
|
|
|
pub enum Conflict {
|
|
|
|
Upstream,
|
2020-02-08 19:14:50 +01:00
|
|
|
Downstream,
|
2017-11-22 22:39:40 +02:00
|
|
|
}
|
2015-03-30 17:46:34 -04:00
|
|
|
|
2017-07-23 22:30:47 +09:00
|
|
|
pub struct OverlapResult<'tcx> {
|
|
|
|
pub impl_header: ty::ImplHeader<'tcx>,
|
|
|
|
pub intercrate_ambiguity_causes: Vec<IntercrateAmbiguityCause>,
|
2018-11-20 11:20:05 -05:00
|
|
|
|
2019-02-08 14:53:55 +01:00
|
|
|
/// `true` if the overlap might've been permitted before the shift
|
2018-11-20 11:20:05 -05:00
|
|
|
/// to universes.
|
|
|
|
pub involves_placeholder: bool,
|
|
|
|
}
|
|
|
|
|
2022-01-23 20:41:46 +00:00
|
|
|
pub fn add_placeholder_note(err: &mut Diagnostic) {
|
2020-02-27 13:34:08 +01:00
|
|
|
err.note(
|
2018-11-20 11:20:05 -05:00
|
|
|
"this behavior recently changed as a result of a bug fix; \
|
2020-02-27 13:34:08 +01:00
|
|
|
see rust-lang/rust#56105 for details",
|
|
|
|
);
|
2017-07-23 22:30:47 +09:00
|
|
|
}
|
|
|
|
|
2018-01-29 18:20:24 -05:00
|
|
|
/// If there are types that satisfy both impls, invokes `on_overlap`
|
|
|
|
/// with a suitably-freshened `ImplHeader` with those types
|
|
|
|
/// substituted. Otherwise, invokes `no_overlap`.
|
2022-01-11 19:32:01 +01:00
|
|
|
#[instrument(skip(tcx, skip_leak_check, on_overlap, no_overlap), level = "debug")]
|
2019-06-21 18:12:39 +02:00
|
|
|
pub fn overlapping_impls<F1, F2, R>(
|
|
|
|
tcx: TyCtxt<'_>,
|
2018-01-29 18:20:24 -05:00
|
|
|
impl1_def_id: DefId,
|
|
|
|
impl2_def_id: DefId,
|
2020-01-24 15:57:01 -05:00
|
|
|
skip_leak_check: SkipLeakCheck,
|
2022-01-30 18:55:22 -03:00
|
|
|
overlap_mode: OverlapMode,
|
2018-01-29 18:20:24 -05:00
|
|
|
on_overlap: F1,
|
|
|
|
no_overlap: F2,
|
|
|
|
) -> R
|
|
|
|
where
|
|
|
|
F1: FnOnce(OverlapResult<'_>) -> R,
|
|
|
|
F2: FnOnce() -> R,
|
2014-09-12 10:54:08 -04:00
|
|
|
{
|
2021-02-04 10:45:17 +01:00
|
|
|
// Before doing expensive operations like entering an inference context, do
|
|
|
|
// a quick check via fast_reject to tell if the impl headers could possibly
|
|
|
|
// unify.
|
|
|
|
let impl1_ref = tcx.impl_trait_ref(impl1_def_id);
|
|
|
|
let impl2_ref = tcx.impl_trait_ref(impl2_def_id);
|
|
|
|
|
2021-02-12 14:04:09 +01:00
|
|
|
// Check if any of the input types definitely do not unify.
|
2021-03-08 15:32:41 -08:00
|
|
|
if iter::zip(
|
|
|
|
impl1_ref.iter().flat_map(|tref| tref.substs.types()),
|
|
|
|
impl2_ref.iter().flat_map(|tref| tref.substs.types()),
|
|
|
|
)
|
|
|
|
.any(|(ty1, ty2)| {
|
2022-02-21 13:44:55 +01:00
|
|
|
let t1 = fast_reject::simplify_type(tcx, ty1, TreatParams::AsPlaceholders);
|
|
|
|
let t2 = fast_reject::simplify_type(tcx, ty2, TreatParams::AsPlaceholders);
|
2022-01-11 19:32:01 +01:00
|
|
|
|
2021-03-08 15:32:41 -08:00
|
|
|
if let (Some(t1), Some(t2)) = (t1, t2) {
|
|
|
|
// Simplified successfully
|
2021-05-07 20:00:02 +02:00
|
|
|
t1 != t2
|
2021-03-08 15:32:41 -08:00
|
|
|
} else {
|
|
|
|
// Types might unify
|
|
|
|
false
|
|
|
|
}
|
|
|
|
}) {
|
2021-02-04 10:45:17 +01:00
|
|
|
// Some types involved are definitely different, so the impls couldn't possibly overlap.
|
|
|
|
debug!("overlapping_impls: fast_reject early-exit");
|
|
|
|
return no_overlap();
|
|
|
|
}
|
2014-10-09 17:19:50 -04:00
|
|
|
|
2019-01-01 23:53:52 +02:00
|
|
|
let overlaps = tcx.infer_ctxt().enter(|infcx| {
|
2020-02-08 19:14:50 +01:00
|
|
|
let selcx = &mut SelectionContext::intercrate(&infcx);
|
2022-01-30 18:55:22 -03:00
|
|
|
overlap(selcx, skip_leak_check, impl1_def_id, impl2_def_id, overlap_mode).is_some()
|
2018-01-26 17:21:43 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
if !overlaps {
|
|
|
|
return no_overlap();
|
|
|
|
}
|
|
|
|
|
|
|
|
// In the case where we detect an error, run the check again, but
|
|
|
|
// this time tracking intercrate ambuiguity causes for better
|
|
|
|
// diagnostics. (These take time and can lead to false errors.)
|
2019-01-01 23:53:52 +02:00
|
|
|
tcx.infer_ctxt().enter(|infcx| {
|
2020-02-08 19:14:50 +01:00
|
|
|
let selcx = &mut SelectionContext::intercrate(&infcx);
|
2018-01-26 17:21:43 -05:00
|
|
|
selcx.enable_tracking_intercrate_ambiguity_causes();
|
2022-01-30 18:55:22 -03:00
|
|
|
on_overlap(
|
|
|
|
overlap(selcx, skip_leak_check, impl1_def_id, impl2_def_id, overlap_mode).unwrap(),
|
|
|
|
)
|
2018-01-29 17:40:13 -05:00
|
|
|
})
|
2015-02-12 12:42:02 -05:00
|
|
|
}
|
|
|
|
|
2019-06-14 01:32:15 +03:00
|
|
|
fn with_fresh_ty_vars<'cx, 'tcx>(
|
|
|
|
selcx: &mut SelectionContext<'cx, 'tcx>,
|
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
|
|
|
impl_def_id: DefId,
|
|
|
|
) -> ty::ImplHeader<'tcx> {
|
2017-05-23 04:19:47 -04:00
|
|
|
let tcx = selcx.tcx();
|
2018-03-06 09:07:27 -07:00
|
|
|
let impl_substs = selcx.infcx().fresh_substs_for_item(DUMMY_SP, impl_def_id);
|
2017-05-23 04:19:47 -04:00
|
|
|
|
|
|
|
let header = ty::ImplHeader {
|
2017-07-03 11:19:51 -07:00
|
|
|
impl_def_id,
|
2018-09-16 20:15:49 +03:00
|
|
|
self_ty: tcx.type_of(impl_def_id).subst(tcx, impl_substs),
|
|
|
|
trait_ref: tcx.impl_trait_ref(impl_def_id).subst(tcx, impl_substs),
|
|
|
|
predicates: tcx.predicates_of(impl_def_id).instantiate(tcx, impl_substs).predicates,
|
|
|
|
};
|
2017-05-23 04:19:47 -04:00
|
|
|
|
|
|
|
let Normalized { value: mut header, obligations } =
|
2020-10-24 02:21:18 +02:00
|
|
|
traits::normalize(selcx, param_env, ObligationCause::dummy(), header);
|
2017-05-23 04:19:47 -04:00
|
|
|
|
|
|
|
header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
|
|
|
|
header
|
|
|
|
}
|
|
|
|
|
2015-12-01 11:26:47 -08:00
|
|
|
/// Can both impl `a` and impl `b` be satisfied by a common type (including
|
2019-02-08 14:53:55 +01:00
|
|
|
/// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
|
2019-06-14 00:48:52 +03:00
|
|
|
fn overlap<'cx, 'tcx>(
|
|
|
|
selcx: &mut SelectionContext<'cx, 'tcx>,
|
2020-01-24 15:57:01 -05:00
|
|
|
skip_leak_check: SkipLeakCheck,
|
2022-01-21 10:50:42 -03:00
|
|
|
impl1_def_id: DefId,
|
|
|
|
impl2_def_id: DefId,
|
2022-01-30 18:55:22 -03:00
|
|
|
overlap_mode: OverlapMode,
|
2018-11-20 11:20:05 -05:00
|
|
|
) -> Option<OverlapResult<'tcx>> {
|
2022-02-03 22:40:29 -03:00
|
|
|
debug!(
|
|
|
|
"overlap(impl1_def_id={:?}, impl2_def_id={:?}, overlap_mode={:?})",
|
|
|
|
impl1_def_id, impl2_def_id, overlap_mode
|
|
|
|
);
|
2015-02-23 13:02:31 -05:00
|
|
|
|
2020-01-24 15:57:01 -05:00
|
|
|
selcx.infcx().probe_maybe_skip_leak_check(skip_leak_check.is_yes(), |snapshot| {
|
2022-02-21 10:40:41 +01:00
|
|
|
overlap_within_probe(selcx, impl1_def_id, impl2_def_id, overlap_mode, snapshot)
|
2020-01-24 15:57:01 -05:00
|
|
|
})
|
2018-11-20 11:20:05 -05:00
|
|
|
}
|
|
|
|
|
2021-12-14 09:44:49 +00:00
|
|
|
fn overlap_within_probe<'cx, 'tcx>(
|
2019-06-14 00:48:52 +03:00
|
|
|
selcx: &mut SelectionContext<'cx, 'tcx>,
|
2022-01-21 10:50:42 -03:00
|
|
|
impl1_def_id: DefId,
|
|
|
|
impl2_def_id: DefId,
|
2022-01-30 18:55:22 -03:00
|
|
|
overlap_mode: OverlapMode,
|
2018-11-20 11:20:05 -05:00
|
|
|
snapshot: &CombinedSnapshot<'_, 'tcx>,
|
|
|
|
) -> Option<OverlapResult<'tcx>> {
|
2022-01-21 11:02:52 -03:00
|
|
|
let infcx = selcx.infcx();
|
2022-01-22 18:16:11 -03:00
|
|
|
|
|
|
|
if overlap_mode.use_negative_impl() {
|
|
|
|
if negative_impl(selcx, impl1_def_id, impl2_def_id)
|
|
|
|
|| negative_impl(selcx, impl2_def_id, impl1_def_id)
|
|
|
|
{
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-07 09:46:53 -04:00
|
|
|
// For the purposes of this check, we don't bring any placeholder
|
2017-05-23 04:19:47 -04:00
|
|
|
// types into scope; instead, we replace the generic types with
|
|
|
|
// fresh type variables, and hence we do our evaluations in an
|
|
|
|
// empty environment.
|
2018-02-10 13:18:02 -05:00
|
|
|
let param_env = ty::ParamEnv::empty();
|
2017-05-23 04:19:47 -04:00
|
|
|
|
2022-01-21 10:50:42 -03:00
|
|
|
let impl1_header = with_fresh_ty_vars(selcx, param_env, impl1_def_id);
|
|
|
|
let impl2_header = with_fresh_ty_vars(selcx, param_env, impl2_def_id);
|
2015-03-30 17:46:34 -04:00
|
|
|
|
2022-01-22 18:16:11 -03:00
|
|
|
let obligations = equate_impl_headers(selcx, &impl1_header, &impl2_header)?;
|
|
|
|
debug!("overlap: unification check succeeded");
|
|
|
|
|
|
|
|
if overlap_mode.use_implicit_negative() {
|
|
|
|
if implicit_negative(selcx, param_env, &impl1_header, impl2_header, obligations) {
|
|
|
|
return None;
|
2022-01-21 12:53:50 -03:00
|
|
|
}
|
2022-01-21 11:02:52 -03:00
|
|
|
}
|
|
|
|
|
2022-02-21 10:40:41 +01:00
|
|
|
// We disable the leak when when creating the `snapshot` by using
|
|
|
|
// `infcx.probe_maybe_disable_leak_check`.
|
|
|
|
if infcx.leak_check(true, snapshot).is_err() {
|
|
|
|
debug!("overlap: leak check failed");
|
|
|
|
return None;
|
2022-01-21 11:02:52 -03:00
|
|
|
}
|
|
|
|
|
|
|
|
let intercrate_ambiguity_causes = selcx.take_intercrate_ambiguity_causes();
|
|
|
|
debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
|
|
|
|
|
|
|
|
let involves_placeholder =
|
|
|
|
matches!(selcx.infcx().region_constraints_added_in_snapshot(snapshot), Some(true));
|
|
|
|
|
|
|
|
let impl_header = selcx.infcx().resolve_vars_if_possible(impl1_header);
|
|
|
|
Some(OverlapResult { impl_header, intercrate_ambiguity_causes, involves_placeholder })
|
|
|
|
}
|
|
|
|
|
2022-01-22 18:16:11 -03:00
|
|
|
fn equate_impl_headers<'cx, 'tcx>(
|
|
|
|
selcx: &mut SelectionContext<'cx, 'tcx>,
|
|
|
|
impl1_header: &ty::ImplHeader<'tcx>,
|
|
|
|
impl2_header: &ty::ImplHeader<'tcx>,
|
|
|
|
) -> Option<PredicateObligations<'tcx>> {
|
|
|
|
// Do `a` and `b` unify? If not, no overlap.
|
2022-02-03 22:40:29 -03:00
|
|
|
debug!("equate_impl_headers(impl1_header={:?}, impl2_header={:?}", impl1_header, impl2_header);
|
2022-01-22 18:16:11 -03:00
|
|
|
selcx
|
|
|
|
.infcx()
|
|
|
|
.at(&ObligationCause::dummy(), ty::ParamEnv::empty())
|
|
|
|
.eq_impl_headers(impl1_header, impl2_header)
|
|
|
|
.map(|infer_ok| infer_ok.obligations)
|
|
|
|
.ok()
|
|
|
|
}
|
|
|
|
|
2022-01-21 11:02:52 -03:00
|
|
|
/// Given impl1 and impl2 check if both impls can be satisfied by a common type (including
|
|
|
|
/// where-clauses) If so, return false, otherwise return true, they are disjoint.
|
2022-01-22 18:16:11 -03:00
|
|
|
fn implicit_negative<'cx, 'tcx>(
|
2022-01-21 11:02:52 -03:00
|
|
|
selcx: &mut SelectionContext<'cx, 'tcx>,
|
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
|
|
|
impl1_header: &ty::ImplHeader<'tcx>,
|
|
|
|
impl2_header: ty::ImplHeader<'tcx>,
|
2022-01-22 18:16:11 -03:00
|
|
|
obligations: PredicateObligations<'tcx>,
|
2022-01-21 11:02:52 -03:00
|
|
|
) -> bool {
|
2021-10-22 09:22:19 -03:00
|
|
|
// There's no overlap if obligations are unsatisfiable or if the obligation negated is
|
|
|
|
// satisfied.
|
|
|
|
//
|
|
|
|
// For example, given these two impl headers:
|
|
|
|
//
|
|
|
|
// `impl<'a> From<&'a str> for Box<dyn Error>`
|
|
|
|
// `impl<E> From<E> for Box<dyn Error> where E: Error`
|
|
|
|
//
|
|
|
|
// So we have:
|
|
|
|
//
|
|
|
|
// `Box<dyn Error>: From<&'?a str>`
|
|
|
|
// `Box<dyn Error>: From<?E>`
|
|
|
|
//
|
|
|
|
// After equating the two headers:
|
|
|
|
//
|
|
|
|
// `Box<dyn Error> = Box<dyn Error>`
|
|
|
|
// So, `?E = &'?a str` and then given the where clause `&'?a str: Error`.
|
|
|
|
//
|
|
|
|
// If the obligation `&'?a str: Error` holds, it means that there's overlap. If that doesn't
|
|
|
|
// hold we need to check if `&'?a str: !Error` holds, if doesn't hold there's overlap because
|
|
|
|
// at some point an impl for `&'?a str: Error` could be added.
|
2022-02-03 22:40:29 -03:00
|
|
|
debug!(
|
|
|
|
"implicit_negative(impl1_header={:?}, impl2_header={:?}, obligations={:?})",
|
|
|
|
impl1_header, impl2_header, obligations
|
|
|
|
);
|
2015-03-30 17:46:34 -04:00
|
|
|
let infcx = selcx.infcx();
|
2022-01-21 10:50:42 -03:00
|
|
|
let opt_failing_obligation = impl1_header
|
2019-12-22 17:42:04 -05:00
|
|
|
.predicates
|
|
|
|
.iter()
|
2020-10-24 02:21:18 +02:00
|
|
|
.copied()
|
2022-01-21 10:50:42 -03:00
|
|
|
.chain(impl2_header.predicates)
|
2019-12-22 17:42:04 -05:00
|
|
|
.map(|p| infcx.resolve_vars_if_possible(p))
|
|
|
|
.map(|p| Obligation {
|
|
|
|
cause: ObligationCause::dummy(),
|
|
|
|
param_env,
|
|
|
|
recursion_depth: 0,
|
|
|
|
predicate: p,
|
|
|
|
})
|
|
|
|
.chain(obligations)
|
2022-02-10 16:39:52 -03:00
|
|
|
.find(|o| !selcx.predicate_may_hold_fatal(o));
|
2015-02-23 13:02:31 -05:00
|
|
|
|
|
|
|
if let Some(failing_obligation) = opt_failing_obligation {
|
2015-06-18 20:25:05 +03:00
|
|
|
debug!("overlap: obligation unsatisfiable {:?}", failing_obligation);
|
2022-01-21 11:02:52 -03:00
|
|
|
true
|
|
|
|
} else {
|
|
|
|
false
|
move leak-check to during coherence, candidate eval
In particular, it no longer occurs during the subtyping check. This is
important for enabling lazy normalization, because the subtyping check
will be producing sub-obligations that could affect its results.
Consider an example like
for<'a> fn(<&'a as Mirror>::Item) =
fn(&'b u8)
where `<T as Mirror>::Item = T` for all `T`. We will wish to produce a
new subobligation like
<'!1 as Mirror>::Item = &'b u8
This will, after being solved, ultimately yield a constraint that `'!1
= 'b` which will fail. But with the leak-check being performed on
subtyping, there is no opportunity to normalize `<'!1 as
Mirror>::Item` (unless we invoke that normalization directly from
within subtyping, and I would prefer that subtyping and unification
are distinct operations rather than part of the trait solving stack).
The reason to keep the leak check during coherence and trait
evaluation is partly for backwards compatibility. The coherence change
permits impls for `fn(T)` and `fn(&T)` to co-exist, and the trait
evaluation change means that we can distinguish those two cases
without ambiguity errors. It also avoids recreating #57639, where we
were incorrectly choosing a where clause that would have failed the
leak check over the impl which succeeds.
The other reason to keep the leak check in those places is that I
think it is actually close to the model we want. To the point, I think
the trait solver ought to have the job of "breaking down"
higher-ranked region obligation like ``!1: '2` into into region
obligations that operate on things in the root universe, at which
point they should be handed off to polonius. The leak check isn't
*really* doing that -- these obligations are still handed to the
region solver to process -- but if/when we do adopt that model, the
decision to pass/fail would be happening in roughly this part of the
code.
This change had somewhat more side-effects than I anticipated. It
seems like there are cases where the leak-check was not being enforced
during method proving and trait selection. I haven't quite tracked
this down but I think it ought to be documented, so that we know what
precisely we are committing to.
One surprising test was `issue-30786.rs`. The behavior there seems a
bit "fishy" to me, but the problem is not related to the leak check
change as far as I can tell, but more to do with the closure signature
inference code and perhaps the associated type projection, which
together seem to be conspiring to produce an unexpected
signature. Nonetheless, it is an example of where changing the
leak-check can have some unexpected consequences: we're now failing to
resolve a method earlier than we were, which suggests we might change
some method resolutions that would have been ambiguous to be
successful.
TODO:
* figure out remainig test failures
* add new coherence tests for the patterns we ARE disallowing
2020-05-20 10:19:36 +00:00
|
|
|
}
|
2015-02-12 12:42:02 -05:00
|
|
|
}
|
|
|
|
|
2022-01-21 12:53:50 -03:00
|
|
|
/// Given impl1 and impl2 check if both impls are never satisfied by a common type (including
|
|
|
|
/// where-clauses) If so, return true, they are disjoint and false otherwise.
|
2022-01-22 18:16:11 -03:00
|
|
|
fn negative_impl<'cx, 'tcx>(
|
2022-01-21 12:53:50 -03:00
|
|
|
selcx: &mut SelectionContext<'cx, 'tcx>,
|
|
|
|
impl1_def_id: DefId,
|
|
|
|
impl2_def_id: DefId,
|
|
|
|
) -> bool {
|
2022-02-03 22:40:29 -03:00
|
|
|
debug!("negative_impl(impl1_def_id={:?}, impl2_def_id={:?})", impl1_def_id, impl2_def_id);
|
2022-01-21 12:53:50 -03:00
|
|
|
let tcx = selcx.infcx().tcx;
|
|
|
|
|
|
|
|
// Create an infcx, taking the predicates of impl1 as assumptions:
|
|
|
|
tcx.infer_ctxt().enter(|infcx| {
|
2022-03-17 22:51:45 -03:00
|
|
|
// create a parameter environment corresponding to a (placeholder) instantiation of impl1
|
2022-03-24 12:27:09 -03:00
|
|
|
let impl_env = tcx.param_env(impl1_def_id);
|
2022-03-24 14:17:54 -03:00
|
|
|
let subject1 = match traits::fully_normalize(
|
|
|
|
&infcx,
|
|
|
|
FulfillmentContext::new(),
|
|
|
|
ObligationCause::dummy(),
|
|
|
|
impl_env,
|
|
|
|
tcx.impl_subject(impl1_def_id),
|
|
|
|
) {
|
|
|
|
Ok(s) => s,
|
|
|
|
Err(err) => bug!("failed to fully normalize {:?}: {:?}", impl1_def_id, err),
|
2022-03-24 12:27:09 -03:00
|
|
|
};
|
2022-03-20 00:12:03 -03:00
|
|
|
|
2022-03-24 12:27:09 -03:00
|
|
|
let (subject2, obligations) =
|
|
|
|
impl_subject_and_obligations(&infcx, impl_env, subject1, impl2_def_id);
|
2022-03-20 00:12:03 -03:00
|
|
|
|
2022-03-24 12:27:09 -03:00
|
|
|
!equate(&infcx, impl_env, impl1_def_id, subject1, subject2, obligations)
|
2022-01-21 12:53:50 -03:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-03-24 12:27:09 -03:00
|
|
|
fn impl_subject_and_obligations<'cx, 'tcx>(
|
2022-03-18 14:07:22 -03:00
|
|
|
infcx: &InferCtxt<'cx, 'tcx>,
|
2022-03-24 12:27:09 -03:00
|
|
|
impl_env: ty::ParamEnv<'tcx>,
|
|
|
|
subject1: ImplSubject<'tcx>,
|
|
|
|
impl2_def_id: DefId,
|
|
|
|
) -> (ImplSubject<'tcx>, Box<dyn Iterator<Item = PredicateObligation<'tcx>> + 'tcx>) {
|
|
|
|
if let ImplSubject::Trait(_) = subject1 {
|
|
|
|
// Attempt to prove that impl2 applies, given all of the above.
|
|
|
|
let selcx = &mut SelectionContext::new(&infcx);
|
|
|
|
let impl2_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl2_def_id);
|
|
|
|
let (impl2_trait_ref, obligations) =
|
|
|
|
impl_trait_ref_and_oblig(selcx, impl_env, impl2_def_id, impl2_substs);
|
|
|
|
|
|
|
|
(ImplSubject::Trait(impl2_trait_ref), Box::new(obligations))
|
|
|
|
} else {
|
2022-03-24 17:47:10 -03:00
|
|
|
// Attempt to prove that impl2 applies, given all of the above.
|
|
|
|
let selcx = &mut SelectionContext::new(&infcx);
|
|
|
|
let impl2_substs = infcx.fresh_substs_for_item(DUMMY_SP, impl2_def_id);
|
|
|
|
let (impl2_ty, obligations) =
|
|
|
|
inherent_impl_and_oblig(selcx, impl_env, impl2_def_id, impl2_substs);
|
|
|
|
|
|
|
|
(ImplSubject::Inherent(impl2_ty), Box::new(obligations))
|
2022-03-24 12:27:09 -03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn equate<'cx, 'tcx>(
|
|
|
|
infcx: &InferCtxt<'cx, 'tcx>,
|
|
|
|
impl_env: ty::ParamEnv<'tcx>,
|
2022-03-18 14:07:22 -03:00
|
|
|
impl1_def_id: DefId,
|
2022-03-24 12:27:09 -03:00
|
|
|
subject1: ImplSubject<'tcx>,
|
|
|
|
subject2: ImplSubject<'tcx>,
|
2022-03-18 14:07:22 -03:00
|
|
|
obligations: impl Iterator<Item = PredicateObligation<'tcx>>,
|
|
|
|
) -> bool {
|
|
|
|
// do the impls unify? If not, not disjoint.
|
2022-03-24 12:27:09 -03:00
|
|
|
let Ok(InferOk { obligations: more_obligations, .. }) =
|
|
|
|
infcx.at(&ObligationCause::dummy(), impl_env).eq(subject1, subject2)
|
|
|
|
else {
|
|
|
|
debug!("explicit_disjoint: {:?} does not unify with {:?}", subject1, subject2);
|
|
|
|
return true;
|
|
|
|
};
|
2022-03-18 14:07:22 -03:00
|
|
|
|
|
|
|
let selcx = &mut SelectionContext::new(&infcx);
|
|
|
|
let opt_failing_obligation = obligations
|
|
|
|
.into_iter()
|
|
|
|
.chain(more_obligations)
|
2022-03-24 12:27:09 -03:00
|
|
|
.find(|o| negative_impl_exists(selcx, impl_env, impl1_def_id, o));
|
2022-03-18 14:07:22 -03:00
|
|
|
|
|
|
|
if let Some(failing_obligation) = opt_failing_obligation {
|
|
|
|
debug!("overlap: obligation unsatisfiable {:?}", failing_obligation);
|
|
|
|
false
|
|
|
|
} else {
|
|
|
|
true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-03-18 14:13:06 -03:00
|
|
|
/// Try to prove that a negative impl exist for the given obligation and its super predicates.
|
2022-03-17 11:26:45 -03:00
|
|
|
#[instrument(level = "debug", skip(selcx))]
|
2022-01-22 21:25:56 -03:00
|
|
|
fn negative_impl_exists<'cx, 'tcx>(
|
2022-01-21 10:53:17 -03:00
|
|
|
selcx: &SelectionContext<'cx, 'tcx>,
|
2022-02-02 14:36:45 -03:00
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
|
|
|
region_context: DefId,
|
2022-01-21 10:53:17 -03:00
|
|
|
o: &PredicateObligation<'tcx>,
|
|
|
|
) -> bool {
|
2022-02-09 19:37:10 -03:00
|
|
|
let infcx = &selcx.infcx().fork();
|
2022-03-17 11:26:45 -03:00
|
|
|
|
2022-03-17 12:09:00 -03:00
|
|
|
if resolve_negative_obligation(infcx, param_env, region_context, o) {
|
|
|
|
return true;
|
|
|
|
}
|
2022-03-17 11:26:45 -03:00
|
|
|
|
2022-03-18 14:13:06 -03:00
|
|
|
// Try to prove a negative obligation exists for super predicates
|
2022-03-17 12:09:00 -03:00
|
|
|
for o in util::elaborate_predicates(infcx.tcx, iter::once(o.predicate)) {
|
|
|
|
if resolve_negative_obligation(infcx, param_env, region_context, &o) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
2022-02-02 14:36:45 -03:00
|
|
|
|
2022-03-17 12:09:00 -03:00
|
|
|
false
|
|
|
|
}
|
2022-03-17 11:26:45 -03:00
|
|
|
|
2022-03-17 12:09:00 -03:00
|
|
|
#[instrument(level = "debug", skip(infcx))]
|
|
|
|
fn resolve_negative_obligation<'cx, 'tcx>(
|
|
|
|
infcx: &InferCtxt<'cx, 'tcx>,
|
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
|
|
|
region_context: DefId,
|
|
|
|
o: &PredicateObligation<'tcx>,
|
|
|
|
) -> bool {
|
|
|
|
let tcx = infcx.tcx;
|
2022-02-02 14:36:45 -03:00
|
|
|
|
2022-03-17 14:55:16 -03:00
|
|
|
let Some(o) = o.flip_polarity(tcx) else {
|
|
|
|
return false;
|
|
|
|
};
|
2022-02-10 16:38:27 -03:00
|
|
|
|
2022-03-17 14:55:16 -03:00
|
|
|
let mut fulfillment_cx = FulfillmentContext::new();
|
|
|
|
fulfillment_cx.register_predicate_obligation(infcx, o);
|
2022-02-02 14:36:45 -03:00
|
|
|
|
2022-03-17 14:55:16 -03:00
|
|
|
let errors = fulfillment_cx.select_all_or_error(infcx);
|
2022-02-02 14:36:45 -03:00
|
|
|
|
2022-03-17 14:55:16 -03:00
|
|
|
if !errors.is_empty() {
|
|
|
|
return false;
|
|
|
|
}
|
2022-03-17 11:26:45 -03:00
|
|
|
|
2022-03-17 14:55:16 -03:00
|
|
|
let mut outlives_env = OutlivesEnvironment::new(param_env);
|
|
|
|
// FIXME -- add "assumed to be well formed" types into the `outlives_env`
|
2022-02-02 14:36:45 -03:00
|
|
|
|
2022-03-17 14:55:16 -03:00
|
|
|
// "Save" the accumulated implied bounds into the outlives environment
|
|
|
|
// (due to the FIXME above, there aren't any, but this step is still needed).
|
|
|
|
// The "body id" is given as `CRATE_HIR_ID`, which is the same body-id used
|
|
|
|
// by the "dummy" causes elsewhere (body-id is only relevant when checking
|
|
|
|
// function bodies with closures).
|
|
|
|
outlives_env.save_implied_bounds(CRATE_HIR_ID);
|
2022-03-17 12:09:00 -03:00
|
|
|
|
2022-03-17 14:55:16 -03:00
|
|
|
infcx.process_registered_region_obligations(
|
|
|
|
outlives_env.region_bound_pairs_map(),
|
|
|
|
Some(tcx.lifetimes.re_root_empty),
|
|
|
|
param_env,
|
|
|
|
);
|
2022-03-17 12:09:00 -03:00
|
|
|
|
2022-03-17 14:55:16 -03:00
|
|
|
let errors = infcx.resolve_regions(region_context, &outlives_env, RegionckMode::default());
|
2022-03-17 12:09:00 -03:00
|
|
|
|
2022-03-17 14:55:16 -03:00
|
|
|
if !errors.is_empty() {
|
|
|
|
return false;
|
2022-03-17 11:26:45 -03:00
|
|
|
}
|
|
|
|
|
2022-03-17 14:55:16 -03:00
|
|
|
true
|
2022-01-21 10:53:17 -03:00
|
|
|
}
|
|
|
|
|
2019-06-14 00:48:52 +03:00
|
|
|
pub fn trait_ref_is_knowable<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
2019-06-12 00:11:55 +03:00
|
|
|
trait_ref: ty::TraitRef<'tcx>,
|
|
|
|
) -> Option<Conflict> {
|
2017-11-22 23:01:51 +02:00
|
|
|
debug!("trait_ref_is_knowable(trait_ref={:?})", trait_ref);
|
|
|
|
if orphan_check_trait_ref(tcx, trait_ref, InCrate::Remote).is_ok() {
|
2017-11-22 22:39:40 +02:00
|
|
|
// A downstream or cousin crate is allowed to implement some
|
|
|
|
// substitution of this trait-ref.
|
2020-02-08 19:14:50 +01:00
|
|
|
return Some(Conflict::Downstream);
|
2017-11-28 14:52:34 +02:00
|
|
|
}
|
|
|
|
|
2017-11-22 22:39:40 +02:00
|
|
|
if trait_ref_is_local_or_fundamental(tcx, trait_ref) {
|
|
|
|
// This is a local or fundamental trait, so future-compatibility
|
|
|
|
// is no concern. We know that downstream/cousin crates are not
|
|
|
|
// allowed to implement a substitution of this trait ref, which
|
|
|
|
// means impls could only come from dependencies of this crate,
|
|
|
|
// which we already know about.
|
|
|
|
return None;
|
|
|
|
}
|
2017-11-22 23:01:51 +02:00
|
|
|
|
2017-11-22 22:39:40 +02:00
|
|
|
// This is a remote non-fundamental trait, so if another crate
|
|
|
|
// can be the "final owner" of a substitution of this trait-ref,
|
|
|
|
// they are allowed to implement it future-compatibly.
|
|
|
|
//
|
|
|
|
// However, if we are a final owner, then nobody else can be,
|
|
|
|
// and if we are an intermediate owner, then we don't care
|
|
|
|
// about future-compatibility, which means that we're OK if
|
|
|
|
// we are an owner.
|
2017-11-22 23:01:51 +02:00
|
|
|
if orphan_check_trait_ref(tcx, trait_ref, InCrate::Local).is_ok() {
|
2017-11-22 22:39:40 +02:00
|
|
|
debug!("trait_ref_is_knowable: orphan check passed");
|
2020-03-20 15:03:11 +01:00
|
|
|
None
|
2017-11-22 22:39:40 +02:00
|
|
|
} else {
|
|
|
|
debug!("trait_ref_is_knowable: nonlocal, nonfundamental, unowned");
|
2020-03-20 15:03:11 +01:00
|
|
|
Some(Conflict::Upstream)
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-14 00:48:52 +03:00
|
|
|
pub fn trait_ref_is_local_or_fundamental<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
2019-06-12 00:11:55 +03:00
|
|
|
trait_ref: ty::TraitRef<'tcx>,
|
|
|
|
) -> bool {
|
2019-05-08 13:21:18 +10:00
|
|
|
trait_ref.def_id.krate == LOCAL_CRATE || tcx.has_attr(trait_ref.def_id, sym::fundamental)
|
2017-08-28 16:50:41 -04:00
|
|
|
}
|
|
|
|
|
Implement new orphan rule that requires that impls of remote traits meet the following two criteria:
- the self type includes some local type; and,
- type parameters in the self type must be constrained by a local type.
A type parameter is called *constrained* if it appears in some type-parameter of a local type.
Here are some examples that are accepted. In all of these examples, I
assume that `Foo` is a trait defined in another crate. If `Foo` were
defined in the local crate, then all the examples would be legal.
- `impl Foo for LocalType`
- `impl<T> Foo<T> for LocalType` -- T does not appear in Self, so it is OK
- `impl<T> Foo<T> for LocalType<T>` -- T here is constrained by LocalType
- `impl<T> Foo<T> for (LocalType<T>, T)` -- T here is constrained by LocalType
Here are some illegal examples (again, these examples assume that
`Foo` is not local to the current crate):
- `impl Foo for int` -- the Self type is not local
- `impl<T> Foo for T` -- T appears in Self unconstrained by a local type
- `impl<T> Foo for (LocalType, T)` -- T appears in Self unconstrained by a local type
This is a [breaking-change]. For the time being, you can opt out of
the new rules by placing `#[old_orphan_check]` on the trait (and
enabling the feature gate where the trait is defined). Longer term,
you should restructure your traits to avoid the problem. Usually this
means changing the order of parameters so that the "central" type
parameter is in the `Self` position.
As an example of that refactoring, consider the `BorrowFrom` trait:
```rust
pub trait BorrowFrom<Sized? Owned> for Sized? {
fn borrow_from(owned: &Owned) -> &Self;
}
```
As defined, this trait is commonly implemented for custom pointer
types, such as `Arc`. Those impls follow the pattern:
```rust
impl<T> BorrowFrom<Arc<T>> for T {...}
```
Unfortunately, this impl is illegal because the self type `T` is not
local to the current crate. Therefore, we are going to change the order of the parameters,
so that `BorrowFrom` becomes `Borrow`:
```rust
pub trait Borrow<Sized? Borrowed> for Sized? {
fn borrow_from(owned: &Self) -> &Borrowed;
}
```
Now the `Arc` impl is written:
```rust
impl<T> Borrow<T> for Arc<T> { ... }
```
This impl is legal because the self type (`Arc<T>`) is local.
2015-01-04 20:35:06 -05:00
|
|
|
pub enum OrphanCheckErr<'tcx> {
|
2019-10-27 10:22:22 -07:00
|
|
|
NonLocalInputType(Vec<(Ty<'tcx>, bool /* Is this the first input type? */)>),
|
2019-11-09 17:32:15 +01:00
|
|
|
UncoveredTy(Ty<'tcx>, Option<Ty<'tcx>>),
|
Fix orphan checking (cc #19470). (This is not a complete fix of #19470 because of the backwards compatibility feature gate.)
This is a [breaking-change]. The new rules require that, for an impl of a trait defined
in some other crate, two conditions must hold:
1. Some type must be local.
2. Every type parameter must appear "under" some local type.
Here are some examples that are legal:
```rust
struct MyStruct<T> { ... }
// Here `T` appears "under' `MyStruct`.
impl<T> Clone for MyStruct<T> { }
// Here `T` appears "under' `MyStruct` as well. Note that it also appears
// elsewhere.
impl<T> Iterator<T> for MyStruct<T> { }
```
Here is an illegal example:
```rust
// Here `U` does not appear "under" `MyStruct` or any other local type.
// We call `U` "uncovered".
impl<T,U> Iterator<U> for MyStruct<T> { }
```
There are a couple of ways to rewrite this last example so that it is
legal:
1. In some cases, the uncovered type parameter (here, `U`) should be converted
into an associated type. This is however a non-local change that requires access
to the original trait. Also, associated types are not fully baked.
2. Add `U` as a type parameter of `MyStruct`:
```rust
struct MyStruct<T,U> { ... }
impl<T,U> Iterator<U> for MyStruct<T,U> { }
```
3. Create a newtype wrapper for `U`
```rust
impl<T,U> Iterator<Wrapper<U>> for MyStruct<T,U> { }
```
Because associated types are not fully baked, which in the case of the
`Hash` trait makes adhering to this rule impossible, you can
temporarily disable this rule in your crate by using
`#![feature(old_orphan_check)]`. Note that the `old_orphan_check`
feature will be removed before 1.0 is released.
2014-12-26 03:30:51 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Checks the coherence orphan rules. `impl_def_id` should be the
|
2019-02-08 14:53:55 +01:00
|
|
|
/// `DefId` of a trait impl. To pass, either the trait must be local, or else
|
Fix orphan checking (cc #19470). (This is not a complete fix of #19470 because of the backwards compatibility feature gate.)
This is a [breaking-change]. The new rules require that, for an impl of a trait defined
in some other crate, two conditions must hold:
1. Some type must be local.
2. Every type parameter must appear "under" some local type.
Here are some examples that are legal:
```rust
struct MyStruct<T> { ... }
// Here `T` appears "under' `MyStruct`.
impl<T> Clone for MyStruct<T> { }
// Here `T` appears "under' `MyStruct` as well. Note that it also appears
// elsewhere.
impl<T> Iterator<T> for MyStruct<T> { }
```
Here is an illegal example:
```rust
// Here `U` does not appear "under" `MyStruct` or any other local type.
// We call `U` "uncovered".
impl<T,U> Iterator<U> for MyStruct<T> { }
```
There are a couple of ways to rewrite this last example so that it is
legal:
1. In some cases, the uncovered type parameter (here, `U`) should be converted
into an associated type. This is however a non-local change that requires access
to the original trait. Also, associated types are not fully baked.
2. Add `U` as a type parameter of `MyStruct`:
```rust
struct MyStruct<T,U> { ... }
impl<T,U> Iterator<U> for MyStruct<T,U> { }
```
3. Create a newtype wrapper for `U`
```rust
impl<T,U> Iterator<Wrapper<U>> for MyStruct<T,U> { }
```
Because associated types are not fully baked, which in the case of the
`Hash` trait makes adhering to this rule impossible, you can
temporarily disable this rule in your crate by using
`#![feature(old_orphan_check)]`. Note that the `old_orphan_check`
feature will be removed before 1.0 is released.
2014-12-26 03:30:51 -05:00
|
|
|
/// two conditions must be satisfied:
|
|
|
|
///
|
Implement new orphan rule that requires that impls of remote traits meet the following two criteria:
- the self type includes some local type; and,
- type parameters in the self type must be constrained by a local type.
A type parameter is called *constrained* if it appears in some type-parameter of a local type.
Here are some examples that are accepted. In all of these examples, I
assume that `Foo` is a trait defined in another crate. If `Foo` were
defined in the local crate, then all the examples would be legal.
- `impl Foo for LocalType`
- `impl<T> Foo<T> for LocalType` -- T does not appear in Self, so it is OK
- `impl<T> Foo<T> for LocalType<T>` -- T here is constrained by LocalType
- `impl<T> Foo<T> for (LocalType<T>, T)` -- T here is constrained by LocalType
Here are some illegal examples (again, these examples assume that
`Foo` is not local to the current crate):
- `impl Foo for int` -- the Self type is not local
- `impl<T> Foo for T` -- T appears in Self unconstrained by a local type
- `impl<T> Foo for (LocalType, T)` -- T appears in Self unconstrained by a local type
This is a [breaking-change]. For the time being, you can opt out of
the new rules by placing `#[old_orphan_check]` on the trait (and
enabling the feature gate where the trait is defined). Longer term,
you should restructure your traits to avoid the problem. Usually this
means changing the order of parameters so that the "central" type
parameter is in the `Self` position.
As an example of that refactoring, consider the `BorrowFrom` trait:
```rust
pub trait BorrowFrom<Sized? Owned> for Sized? {
fn borrow_from(owned: &Owned) -> &Self;
}
```
As defined, this trait is commonly implemented for custom pointer
types, such as `Arc`. Those impls follow the pattern:
```rust
impl<T> BorrowFrom<Arc<T>> for T {...}
```
Unfortunately, this impl is illegal because the self type `T` is not
local to the current crate. Therefore, we are going to change the order of the parameters,
so that `BorrowFrom` becomes `Borrow`:
```rust
pub trait Borrow<Sized? Borrowed> for Sized? {
fn borrow_from(owned: &Self) -> &Borrowed;
}
```
Now the `Arc` impl is written:
```rust
impl<T> Borrow<T> for Arc<T> { ... }
```
This impl is legal because the self type (`Arc<T>`) is local.
2015-01-04 20:35:06 -05:00
|
|
|
/// 1. All type parameters in `Self` must be "covered" by some local type constructor.
|
|
|
|
/// 2. Some local type must appear in `Self`.
|
2019-12-22 17:42:04 -05:00
|
|
|
pub fn orphan_check(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Result<(), OrphanCheckErr<'_>> {
|
2015-06-18 20:25:05 +03:00
|
|
|
debug!("orphan_check({:?})", impl_def_id);
|
2014-09-12 10:54:08 -04:00
|
|
|
|
|
|
|
// We only except this routine to be invoked on implementations
|
|
|
|
// of a trait, not inherent implementations.
|
2015-06-25 23:42:17 +03:00
|
|
|
let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap();
|
2015-06-18 20:25:05 +03:00
|
|
|
debug!("orphan_check: trait_ref={:?}", trait_ref);
|
2014-09-12 10:54:08 -04:00
|
|
|
|
Fix orphan checking (cc #19470). (This is not a complete fix of #19470 because of the backwards compatibility feature gate.)
This is a [breaking-change]. The new rules require that, for an impl of a trait defined
in some other crate, two conditions must hold:
1. Some type must be local.
2. Every type parameter must appear "under" some local type.
Here are some examples that are legal:
```rust
struct MyStruct<T> { ... }
// Here `T` appears "under' `MyStruct`.
impl<T> Clone for MyStruct<T> { }
// Here `T` appears "under' `MyStruct` as well. Note that it also appears
// elsewhere.
impl<T> Iterator<T> for MyStruct<T> { }
```
Here is an illegal example:
```rust
// Here `U` does not appear "under" `MyStruct` or any other local type.
// We call `U` "uncovered".
impl<T,U> Iterator<U> for MyStruct<T> { }
```
There are a couple of ways to rewrite this last example so that it is
legal:
1. In some cases, the uncovered type parameter (here, `U`) should be converted
into an associated type. This is however a non-local change that requires access
to the original trait. Also, associated types are not fully baked.
2. Add `U` as a type parameter of `MyStruct`:
```rust
struct MyStruct<T,U> { ... }
impl<T,U> Iterator<U> for MyStruct<T,U> { }
```
3. Create a newtype wrapper for `U`
```rust
impl<T,U> Iterator<Wrapper<U>> for MyStruct<T,U> { }
```
Because associated types are not fully baked, which in the case of the
`Hash` trait makes adhering to this rule impossible, you can
temporarily disable this rule in your crate by using
`#![feature(old_orphan_check)]`. Note that the `old_orphan_check`
feature will be removed before 1.0 is released.
2014-12-26 03:30:51 -05:00
|
|
|
// If the *trait* is local to the crate, ok.
|
2015-08-16 09:06:23 -04:00
|
|
|
if trait_ref.def_id.is_local() {
|
2019-12-22 17:42:04 -05:00
|
|
|
debug!("trait {:?} is local to current crate", trait_ref.def_id);
|
Fix orphan checking (cc #19470). (This is not a complete fix of #19470 because of the backwards compatibility feature gate.)
This is a [breaking-change]. The new rules require that, for an impl of a trait defined
in some other crate, two conditions must hold:
1. Some type must be local.
2. Every type parameter must appear "under" some local type.
Here are some examples that are legal:
```rust
struct MyStruct<T> { ... }
// Here `T` appears "under' `MyStruct`.
impl<T> Clone for MyStruct<T> { }
// Here `T` appears "under' `MyStruct` as well. Note that it also appears
// elsewhere.
impl<T> Iterator<T> for MyStruct<T> { }
```
Here is an illegal example:
```rust
// Here `U` does not appear "under" `MyStruct` or any other local type.
// We call `U` "uncovered".
impl<T,U> Iterator<U> for MyStruct<T> { }
```
There are a couple of ways to rewrite this last example so that it is
legal:
1. In some cases, the uncovered type parameter (here, `U`) should be converted
into an associated type. This is however a non-local change that requires access
to the original trait. Also, associated types are not fully baked.
2. Add `U` as a type parameter of `MyStruct`:
```rust
struct MyStruct<T,U> { ... }
impl<T,U> Iterator<U> for MyStruct<T,U> { }
```
3. Create a newtype wrapper for `U`
```rust
impl<T,U> Iterator<Wrapper<U>> for MyStruct<T,U> { }
```
Because associated types are not fully baked, which in the case of the
`Hash` trait makes adhering to this rule impossible, you can
temporarily disable this rule in your crate by using
`#![feature(old_orphan_check)]`. Note that the `old_orphan_check`
feature will be removed before 1.0 is released.
2014-12-26 03:30:51 -05:00
|
|
|
return Ok(());
|
2014-09-12 10:54:08 -04:00
|
|
|
}
|
|
|
|
|
2017-11-22 23:01:51 +02:00
|
|
|
orphan_check_trait_ref(tcx, trait_ref, InCrate::Local)
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
|
|
|
|
2019-02-08 14:53:55 +01:00
|
|
|
/// Checks whether a trait-ref is potentially implementable by a crate.
|
2017-11-29 20:50:26 +02:00
|
|
|
///
|
|
|
|
/// The current rule is that a trait-ref orphan checks in a crate C:
|
|
|
|
///
|
|
|
|
/// 1. Order the parameters in the trait-ref in subst order - Self first,
|
2018-11-27 02:59:49 +00:00
|
|
|
/// others linearly (e.g., `<U as Foo<V, W>>` is U < V < W).
|
2017-11-29 20:50:26 +02:00
|
|
|
/// 2. Of these type parameters, there is at least one type parameter
|
|
|
|
/// in which, walking the type as a tree, you can reach a type local
|
|
|
|
/// to C where all types in-between are fundamental types. Call the
|
|
|
|
/// first such parameter the "local key parameter".
|
2018-11-27 02:59:49 +00:00
|
|
|
/// - e.g., `Box<LocalType>` is OK, because you can visit LocalType
|
2017-11-29 20:50:26 +02:00
|
|
|
/// going through `Box`, which is fundamental.
|
|
|
|
/// - similarly, `FundamentalPair<Vec<()>, Box<LocalType>>` is OK for
|
|
|
|
/// the same reason.
|
|
|
|
/// - but (knowing that `Vec<T>` is non-fundamental, and assuming it's
|
|
|
|
/// not local), `Vec<LocalType>` is bad, because `Vec<->` is between
|
|
|
|
/// the local type and the type parameter.
|
2020-07-20 23:18:06 +02:00
|
|
|
/// 3. Before this local type, no generic type parameter of the impl must
|
|
|
|
/// be reachable through fundamental types.
|
|
|
|
/// - e.g. `impl<T> Trait<LocalType> for Vec<T>` is fine, as `Vec` is not fundamental.
|
|
|
|
/// - while `impl<T> Trait<LocalType for Box<T>` results in an error, as `T` is
|
|
|
|
/// reachable through the fundamental type `Box`.
|
2017-11-29 20:50:26 +02:00
|
|
|
/// 4. Every type in the local key parameter not known in C, going
|
|
|
|
/// through the parameter's type tree, must appear only as a subtree of
|
|
|
|
/// a type local to C, with only fundamental types between the type
|
|
|
|
/// local to C and the local key parameter.
|
2018-11-27 02:59:49 +00:00
|
|
|
/// - e.g., `Vec<LocalType<T>>>` (or equivalently `Box<Vec<LocalType<T>>>`)
|
2017-11-29 20:50:26 +02:00
|
|
|
/// is bad, because the only local type with `T` as a subtree is
|
|
|
|
/// `LocalType<T>`, and `Vec<->` is between it and the type parameter.
|
|
|
|
/// - similarly, `FundamentalPair<LocalType<T>, T>` is bad, because
|
2018-02-16 15:56:50 +01:00
|
|
|
/// the second occurrence of `T` is not a subtree of *any* local type.
|
2017-11-29 20:50:26 +02:00
|
|
|
/// - however, `LocalType<Vec<T>>` is OK, because `T` is a subtree of
|
|
|
|
/// `LocalType<Vec<T>>`, which is local and has no types between it and
|
|
|
|
/// the type parameter.
|
|
|
|
///
|
|
|
|
/// The orphan rules actually serve several different purposes:
|
|
|
|
///
|
2018-11-27 02:59:49 +00:00
|
|
|
/// 1. They enable link-safety - i.e., 2 mutually-unknowing crates (where
|
2017-11-29 20:50:26 +02:00
|
|
|
/// every type local to one crate is unknown in the other) can't implement
|
|
|
|
/// the same trait-ref. This follows because it can be seen that no such
|
|
|
|
/// type can orphan-check in 2 such crates.
|
|
|
|
///
|
|
|
|
/// To check that a local impl follows the orphan rules, we check it in
|
|
|
|
/// InCrate::Local mode, using type parameters for the "generic" types.
|
|
|
|
///
|
|
|
|
/// 2. They ground negative reasoning for coherence. If a user wants to
|
|
|
|
/// write both a conditional blanket impl and a specific impl, we need to
|
|
|
|
/// make sure they do not overlap. For example, if we write
|
|
|
|
/// ```
|
|
|
|
/// impl<T> IntoIterator for Vec<T>
|
|
|
|
/// impl<T: Iterator> IntoIterator for T
|
|
|
|
/// ```
|
2017-12-05 15:43:37 +02:00
|
|
|
/// We need to be able to prove that `Vec<$0>: !Iterator` for every type $0.
|
2017-11-29 20:50:26 +02:00
|
|
|
/// We can observe that this holds in the current crate, but we need to make
|
|
|
|
/// sure this will also hold in all unknown crates (both "independent" crates,
|
|
|
|
/// which we need for link-safety, and also child crates, because we don't want
|
|
|
|
/// child crates to get error for impl conflicts in a *dependency*).
|
|
|
|
///
|
|
|
|
/// For that, we only allow negative reasoning if, for every assignment to the
|
|
|
|
/// inference variables, every unknown crate would get an orphan error if they
|
|
|
|
/// try to implement this trait-ref. To check for this, we use InCrate::Remote
|
|
|
|
/// mode. That is sound because we already know all the impls from known crates.
|
|
|
|
///
|
2020-05-01 22:28:15 +02:00
|
|
|
/// 3. For non-`#[fundamental]` traits, they guarantee that parent crates can
|
2017-11-29 20:50:26 +02:00
|
|
|
/// add "non-blanket" impls without breaking negative reasoning in dependent
|
|
|
|
/// crates. This is the "rebalancing coherence" (RFC 1023) restriction.
|
|
|
|
///
|
|
|
|
/// For that, we only a allow crate to perform negative reasoning on
|
2020-05-01 22:28:15 +02:00
|
|
|
/// non-local-non-`#[fundamental]` only if there's a local key parameter as per (2).
|
2017-11-29 20:50:26 +02:00
|
|
|
///
|
|
|
|
/// Because we never perform negative reasoning generically (coherence does
|
|
|
|
/// not involve type parameters), this can be interpreted as doing the full
|
|
|
|
/// orphan check (using InCrate::Local mode), substituting non-local known
|
|
|
|
/// types for all inference variables.
|
|
|
|
///
|
|
|
|
/// This allows for crates to future-compatibly add impls as long as they
|
|
|
|
/// can't apply to types with a key parameter in a child crate - applying
|
|
|
|
/// the rules, this basically means that every type parameter in the impl
|
|
|
|
/// must appear behind a non-fundamental type (because this is not a
|
|
|
|
/// type-system requirement, crate owners might also go for "semantic
|
|
|
|
/// future-compatibility" involving things such as sealed traits, but
|
|
|
|
/// the above requirement is sufficient, and is necessary in "open world"
|
|
|
|
/// cases).
|
|
|
|
///
|
|
|
|
/// Note that this function is never called for types that have both type
|
|
|
|
/// parameters and inference variables.
|
2019-06-12 00:11:55 +03:00
|
|
|
fn orphan_check_trait_ref<'tcx>(
|
2019-10-13 11:25:30 -07:00
|
|
|
tcx: TyCtxt<'tcx>,
|
2019-06-12 00:11:55 +03:00
|
|
|
trait_ref: ty::TraitRef<'tcx>,
|
|
|
|
in_crate: InCrate,
|
|
|
|
) -> Result<(), OrphanCheckErr<'tcx>> {
|
2019-12-22 17:42:04 -05:00
|
|
|
debug!("orphan_check_trait_ref(trait_ref={:?}, in_crate={:?})", trait_ref, in_crate);
|
2015-03-30 17:46:34 -04:00
|
|
|
|
2022-01-12 03:19:52 +00:00
|
|
|
if trait_ref.needs_infer() && trait_ref.needs_subst() {
|
2019-12-22 17:42:04 -05:00
|
|
|
bug!(
|
|
|
|
"can't orphan check a trait ref with both params and inference variables {:?}",
|
|
|
|
trait_ref
|
|
|
|
);
|
2017-11-29 20:50:26 +02:00
|
|
|
}
|
|
|
|
|
2019-10-26 17:28:02 +02:00
|
|
|
// Given impl<P1..=Pn> Trait<T1..=Tn> for T0, an impl is valid only
|
|
|
|
// if at least one of the following is true:
|
|
|
|
//
|
|
|
|
// - Trait is a local trait
|
|
|
|
// (already checked in orphan_check prior to calling this function)
|
|
|
|
// - All of
|
|
|
|
// - At least one of the types T0..=Tn must be a local type.
|
|
|
|
// Let Ti be the first such type.
|
|
|
|
// - No uncovered type parameters P1..=Pn may appear in T0..Ti (excluding Ti)
|
|
|
|
//
|
|
|
|
fn uncover_fundamental_ty<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
ty: Ty<'tcx>,
|
|
|
|
in_crate: InCrate,
|
|
|
|
) -> Vec<Ty<'tcx>> {
|
2020-07-20 23:18:06 +02:00
|
|
|
// FIXME: this is currently somewhat overly complicated,
|
|
|
|
// but fixing this requires a more complicated refactor.
|
2020-07-17 21:40:47 +02:00
|
|
|
if !contained_non_local_types(tcx, ty, in_crate).is_empty() {
|
2020-03-20 05:28:17 +02:00
|
|
|
if let Some(inner_tys) = fundamental_ty_inner_tys(tcx, ty) {
|
|
|
|
return inner_tys
|
|
|
|
.flat_map(|ty| uncover_fundamental_ty(tcx, ty, in_crate))
|
|
|
|
.collect();
|
|
|
|
}
|
2019-09-17 14:40:36 +02:00
|
|
|
}
|
2020-03-20 05:28:17 +02:00
|
|
|
|
|
|
|
vec![ty]
|
2019-10-26 17:28:02 +02:00
|
|
|
}
|
2019-09-17 14:40:36 +02:00
|
|
|
|
2019-10-26 17:28:02 +02:00
|
|
|
let mut non_local_spans = vec![];
|
2020-03-23 06:04:03 +02:00
|
|
|
for (i, input_ty) in trait_ref
|
|
|
|
.substs
|
|
|
|
.types()
|
|
|
|
.flat_map(|ty| uncover_fundamental_ty(tcx, ty, in_crate))
|
|
|
|
.enumerate()
|
2019-10-26 17:28:02 +02:00
|
|
|
{
|
|
|
|
debug!("orphan_check_trait_ref: check ty `{:?}`", input_ty);
|
2020-07-17 21:40:47 +02:00
|
|
|
let non_local_tys = contained_non_local_types(tcx, input_ty, in_crate);
|
|
|
|
if non_local_tys.is_empty() {
|
2019-10-26 17:28:02 +02:00
|
|
|
debug!("orphan_check_trait_ref: ty_is_local `{:?}`", input_ty);
|
|
|
|
return Ok(());
|
2020-08-03 00:49:11 +02:00
|
|
|
} else if let ty::Param(_) = input_ty.kind() {
|
2019-10-26 17:28:02 +02:00
|
|
|
debug!("orphan_check_trait_ref: uncovered ty: `{:?}`", input_ty);
|
2019-11-09 17:32:15 +01:00
|
|
|
let local_type = trait_ref
|
2020-03-23 06:04:03 +02:00
|
|
|
.substs
|
|
|
|
.types()
|
2019-11-09 17:32:15 +01:00
|
|
|
.flat_map(|ty| uncover_fundamental_ty(tcx, ty, in_crate))
|
Overhaul `TyS` and `Ty`.
Specifically, change `Ty` from this:
```
pub type Ty<'tcx> = &'tcx TyS<'tcx>;
```
to this
```
pub struct Ty<'tcx>(Interned<'tcx, TyS<'tcx>>);
```
There are two benefits to this.
- It's now a first class type, so we can define methods on it. This
means we can move a lot of methods away from `TyS`, leaving `TyS` as a
barely-used type, which is appropriate given that it's not meant to
be used directly.
- The uniqueness requirement is now explicit, via the `Interned` type.
E.g. the pointer-based `Eq` and `Hash` comes from `Interned`, rather
than via `TyS`, which wasn't obvious at all.
Much of this commit is boring churn. The interesting changes are in
these files:
- compiler/rustc_middle/src/arena.rs
- compiler/rustc_middle/src/mir/visit.rs
- compiler/rustc_middle/src/ty/context.rs
- compiler/rustc_middle/src/ty/mod.rs
Specifically:
- Most mentions of `TyS` are removed. It's very much a dumb struct now;
`Ty` has all the smarts.
- `TyS` now has `crate` visibility instead of `pub`.
- `TyS::make_for_test` is removed in favour of the static `BOOL_TY`,
which just works better with the new structure.
- The `Eq`/`Ord`/`Hash` impls are removed from `TyS`. `Interned`s impls
of `Eq`/`Hash` now suffice. `Ord` is now partly on `Interned`
(pointer-based, for the `Equal` case) and partly on `TyS`
(contents-based, for the other cases).
- There are many tedious sigil adjustments, i.e. adding or removing `*`
or `&`. They seem to be unavoidable.
2022-01-25 14:13:38 +11:00
|
|
|
.find(|ty| ty_is_local_constructor(*ty, in_crate));
|
2019-11-09 17:32:15 +01:00
|
|
|
|
|
|
|
debug!("orphan_check_trait_ref: uncovered ty local_type: `{:?}`", local_type);
|
|
|
|
|
2019-12-22 17:42:04 -05:00
|
|
|
return Err(OrphanCheckErr::UncoveredTy(input_ty, local_type));
|
2018-11-20 23:37:19 +01:00
|
|
|
}
|
2020-07-17 21:40:47 +02:00
|
|
|
|
2021-12-08 22:56:26 +01:00
|
|
|
non_local_spans.extend(non_local_tys.into_iter().map(|input_ty| (input_ty, i == 0)));
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
2019-10-26 17:28:02 +02:00
|
|
|
// If we exit above loop, never found a local type.
|
|
|
|
debug!("orphan_check_trait_ref: no local type");
|
|
|
|
Err(OrphanCheckErr::NonLocalInputType(non_local_spans))
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
|
|
|
|
2020-07-17 21:40:47 +02:00
|
|
|
/// Returns a list of relevant non-local types for `ty`.
|
|
|
|
///
|
|
|
|
/// This is just `ty` itself unless `ty` is `#[fundamental]`,
|
|
|
|
/// in which case we recursively look into this type.
|
2020-07-20 22:34:26 +02:00
|
|
|
///
|
|
|
|
/// If `ty` is local itself, this method returns an empty `Vec`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// - `u32` is not local, so this returns `[u32]`.
|
|
|
|
/// - for `Foo<u32>`, where `Foo` is a local type, this returns `[]`.
|
|
|
|
/// - `&mut u32` returns `[u32]`, as `&mut` is a fundamental type, similar to `Box`.
|
|
|
|
/// - `Box<Foo<u32>>` returns `[]`, as `Box` is a fundamental type and `Foo` is local.
|
2021-12-14 09:44:49 +00:00
|
|
|
fn contained_non_local_types<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
ty: Ty<'tcx>,
|
|
|
|
in_crate: InCrate,
|
|
|
|
) -> Vec<Ty<'tcx>> {
|
2020-07-17 21:12:47 +02:00
|
|
|
if ty_is_local_constructor(ty, in_crate) {
|
2020-07-17 21:40:47 +02:00
|
|
|
Vec::new()
|
2020-07-17 21:12:47 +02:00
|
|
|
} else {
|
2020-07-17 21:40:47 +02:00
|
|
|
match fundamental_ty_inner_tys(tcx, ty) {
|
|
|
|
Some(inner_tys) => {
|
|
|
|
inner_tys.flat_map(|ty| contained_non_local_types(tcx, ty, in_crate)).collect()
|
|
|
|
}
|
|
|
|
None => vec![ty],
|
|
|
|
}
|
2019-10-13 11:25:30 -07:00
|
|
|
}
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
|
|
|
|
2020-03-20 05:28:17 +02:00
|
|
|
/// For `#[fundamental]` ADTs and `&T` / `&mut T`, returns `Some` with the
|
|
|
|
/// type parameters of the ADT, or `T`, respectively. For non-fundamental
|
|
|
|
/// types, returns `None`.
|
2021-12-14 09:44:49 +00:00
|
|
|
fn fundamental_ty_inner_tys<'tcx>(
|
2020-03-20 05:28:17 +02:00
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
ty: Ty<'tcx>,
|
|
|
|
) -> Option<impl Iterator<Item = Ty<'tcx>>> {
|
2020-08-03 00:49:11 +02:00
|
|
|
let (first_ty, rest_tys) = match *ty.kind() {
|
2020-03-20 05:28:17 +02:00
|
|
|
ty::Ref(_, ty, _) => (ty, ty::subst::InternalSubsts::empty().types()),
|
|
|
|
ty::Adt(def, substs) if def.is_fundamental() => {
|
|
|
|
let mut types = substs.types();
|
|
|
|
|
|
|
|
// FIXME(eddyb) actually validate `#[fundamental]` up-front.
|
|
|
|
match types.next() {
|
|
|
|
None => {
|
|
|
|
tcx.sess.span_err(
|
2022-03-05 07:28:41 +11:00
|
|
|
tcx.def_span(def.did()),
|
2020-03-20 05:28:17 +02:00
|
|
|
"`#[fundamental]` requires at least one type parameter",
|
|
|
|
);
|
|
|
|
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
Some(first_ty) => (first_ty, types),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
_ => return None,
|
|
|
|
};
|
|
|
|
|
|
|
|
Some(iter::once(first_ty).chain(rest_tys))
|
2015-03-30 17:46:34 -04:00
|
|
|
}
|
|
|
|
|
2017-11-22 23:01:51 +02:00
|
|
|
fn def_id_is_local(def_id: DefId, in_crate: InCrate) -> bool {
|
|
|
|
match in_crate {
|
|
|
|
// The type is local to *this* crate - it will not be
|
|
|
|
// local in any other crate.
|
|
|
|
InCrate::Remote => false,
|
2019-12-22 17:42:04 -05:00
|
|
|
InCrate::Local => def_id.is_local(),
|
2017-11-22 22:39:40 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-07-17 21:12:47 +02:00
|
|
|
fn ty_is_local_constructor(ty: Ty<'_>, in_crate: InCrate) -> bool {
|
2020-07-20 22:34:26 +02:00
|
|
|
debug!("ty_is_local_constructor({:?})", ty);
|
2014-09-12 10:54:08 -04:00
|
|
|
|
2020-08-03 00:49:11 +02:00
|
|
|
match *ty.kind() {
|
2019-12-22 17:42:04 -05:00
|
|
|
ty::Bool
|
|
|
|
| ty::Char
|
|
|
|
| ty::Int(..)
|
|
|
|
| ty::Uint(..)
|
|
|
|
| ty::Float(..)
|
|
|
|
| ty::Str
|
|
|
|
| ty::FnDef(..)
|
|
|
|
| ty::FnPtr(_)
|
|
|
|
| ty::Array(..)
|
|
|
|
| ty::Slice(..)
|
|
|
|
| ty::RawPtr(..)
|
|
|
|
| ty::Ref(..)
|
|
|
|
| ty::Never
|
|
|
|
| ty::Tuple(..)
|
|
|
|
| ty::Param(..)
|
2020-07-17 21:12:47 +02:00
|
|
|
| ty::Projection(..) => false,
|
2014-09-12 10:54:08 -04:00
|
|
|
|
2018-11-02 18:48:24 +01:00
|
|
|
ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) => match in_crate {
|
2020-07-17 21:12:47 +02:00
|
|
|
InCrate::Local => false,
|
2017-11-22 23:01:51 +02:00
|
|
|
// The inference variable might be unified with a local
|
|
|
|
// type in that remote crate.
|
2020-07-17 21:12:47 +02:00
|
|
|
InCrate::Remote => true,
|
2017-11-22 22:39:40 +02:00
|
|
|
},
|
2014-09-12 10:54:08 -04:00
|
|
|
|
2022-03-05 07:28:41 +11:00
|
|
|
ty::Adt(def, _) => def_id_is_local(def.did(), in_crate),
|
2020-07-17 21:12:47 +02:00
|
|
|
ty::Foreign(did) => def_id_is_local(did, in_crate),
|
2019-11-20 17:15:42 -05:00
|
|
|
ty::Opaque(..) => {
|
|
|
|
// This merits some explanation.
|
|
|
|
// Normally, opaque types are not involed when performing
|
|
|
|
// coherence checking, since it is illegal to directly
|
|
|
|
// implement a trait on an opaque type. However, we might
|
|
|
|
// end up looking at an opaque type during coherence checking
|
|
|
|
// if an opaque type gets used within another type (e.g. as
|
|
|
|
// a type parameter). This requires us to decide whether or
|
|
|
|
// not an opaque type should be considered 'local' or not.
|
|
|
|
//
|
|
|
|
// We choose to treat all opaque types as non-local, even
|
|
|
|
// those that appear within the same crate. This seems
|
2020-03-06 12:13:55 +01:00
|
|
|
// somewhat surprising at first, but makes sense when
|
2019-11-20 17:15:42 -05:00
|
|
|
// you consider that opaque types are supposed to hide
|
|
|
|
// the underlying type *within the same crate*. When an
|
|
|
|
// opaque type is used from outside the module
|
|
|
|
// where it is declared, it should be impossible to observe
|
2020-07-17 21:12:47 +02:00
|
|
|
// anything about it other than the traits that it implements.
|
2019-11-20 17:15:42 -05:00
|
|
|
//
|
|
|
|
// The alternative would be to look at the underlying type
|
|
|
|
// to determine whether or not the opaque type itself should
|
|
|
|
// be considered local. However, this could make it a breaking change
|
|
|
|
// to switch the underlying ('defining') type from a local type
|
|
|
|
// to a remote type. This would violate the rule that opaque
|
|
|
|
// types should be completely opaque apart from the traits
|
|
|
|
// that they implement, so we don't use this behavior.
|
2020-07-17 21:12:47 +02:00
|
|
|
false
|
Fix coherence checking for impl trait in type aliases
Fixes #63677
RFC #2071 (impl-trait-existential-types) does not explicitly state how
impl trait type alises should interact with coherence. However, there's
only one choice which makes sense - coherence should look at the
underlying type (i.e. the 'defining' type of the impl trait) of the type
alias, just like we do for non-impl-trait type aliases.
Specifically, impl trait type alises which resolve to a local type
should be treated like a local type with respect to coherence (e.g.
impl trait type aliases which resolve to a forieign type should be
treated as a foreign type, and those that resolve to a local type should
be treated as a local type).
Since neither inherent impls nor direct trait impl (i.e. `impl MyType`
or `impl MyTrait for MyType`) are allowd for type aliases, this
usually does not come up. Before we ever attempt to do coherence
checking, we will have errored out if an impl trait type alias was used
directly in an 'impl' clause.
However, during trait selection, we sometimes need to prove bounds like
'T: Sized' for some type 'T'. If 'T' is an impl trait type alias, this
requires to know the coherence behavior for impl trait type aliases when
we perform coherence checking.
Note: Since determining the underlying type of an impl trait type alias
requires us to perform body type checking, this commit causes us to type
check some bodies easlier than we otherwise would have. However, since
this is done through a query, this shouldn't cause any problems
For completeness, I've added an additional test of the coherence-related
behavior of impl trait type aliases.
2019-08-26 21:32:14 -04:00
|
|
|
}
|
2017-09-03 19:53:58 +01:00
|
|
|
|
2021-04-06 18:17:50 -07:00
|
|
|
ty::Closure(..) => {
|
|
|
|
// Similar to the `Opaque` case (#83613).
|
|
|
|
false
|
|
|
|
}
|
|
|
|
|
2018-12-04 13:28:06 +02:00
|
|
|
ty::Dynamic(ref tt, ..) => {
|
|
|
|
if let Some(principal) = tt.principal() {
|
2020-07-17 21:12:47 +02:00
|
|
|
def_id_is_local(principal.def_id(), in_crate)
|
2018-12-04 13:28:06 +02:00
|
|
|
} else {
|
2020-07-17 21:12:47 +02:00
|
|
|
false
|
2018-12-04 13:28:06 +02:00
|
|
|
}
|
|
|
|
}
|
2014-09-12 10:54:08 -04:00
|
|
|
|
2020-07-17 21:12:47 +02:00
|
|
|
ty::Error(_) => true,
|
2016-01-02 04:57:55 -05:00
|
|
|
|
2021-04-06 18:17:50 -07:00
|
|
|
ty::Generator(..) | ty::GeneratorWitness(..) => {
|
2020-05-12 01:56:29 -04:00
|
|
|
bug!("ty_is_local invoked on unexpected type: {:?}", ty)
|
|
|
|
}
|
2014-09-12 10:54:08 -04:00
|
|
|
}
|
|
|
|
}
|