2020-03-06 14:17:12 +00:00
|
|
|
//! See Rustc Dev Guide chapters on [trait-resolution] and [trait-specialization] for more info on
|
|
|
|
//! how this works.
|
2018-02-25 21:24:14 +00:00
|
|
|
//!
|
2020-03-09 21:33:04 +00: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 14:54:08 +00:00
|
|
|
|
2022-02-02 17:36:45 +00:00
|
|
|
use crate::infer::outlives::env::OutlivesEnvironment;
|
2023-05-23 16:56:25 +00:00
|
|
|
use crate::infer::InferOk;
|
2023-09-20 19:41:07 +00:00
|
|
|
use crate::solve::inspect::{InspectGoal, ProofTreeInferCtxtExt, ProofTreeVisitor};
|
2024-05-01 21:22:39 +00:00
|
|
|
use crate::solve::{deeply_normalize_for_diagnostics, inspect};
|
2023-12-05 17:29:36 +00:00
|
|
|
use crate::traits::select::IntercrateAmbiguityCause;
|
2023-09-20 19:41:07 +00:00
|
|
|
use crate::traits::NormalizeExt;
|
2020-01-24 20:57:01 +00:00
|
|
|
use crate::traits::SkipLeakCheck;
|
2024-06-01 18:12:34 +00:00
|
|
|
use crate::traits::{util, FulfillmentErrorCode};
|
2021-10-23 03:03:33 +00:00
|
|
|
use crate::traits::{
|
2024-02-16 17:56:15 +00:00
|
|
|
Obligation, ObligationCause, PredicateObligation, PredicateObligations, SelectionContext,
|
2021-10-23 03:03:33 +00:00
|
|
|
};
|
2022-07-09 17:48:53 +00:00
|
|
|
use rustc_data_structures::fx::FxIndexSet;
|
2024-02-22 23:20:45 +00:00
|
|
|
use rustc_errors::{Diag, EmissionGuarantee};
|
2023-11-14 12:55:59 +00:00
|
|
|
use rustc_hir::def::DefKind;
|
2023-10-15 11:40:17 +00:00
|
|
|
use rustc_hir::def_id::DefId;
|
2023-05-09 20:18:22 +00:00
|
|
|
use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
|
2024-05-08 22:06:59 +00:00
|
|
|
use rustc_middle::bug;
|
2023-09-20 19:41:07 +00:00
|
|
|
use rustc_middle::traits::query::NoSolution;
|
2023-11-20 14:01:31 +00:00
|
|
|
use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal};
|
2022-01-30 21:55:22 +00:00
|
|
|
use rustc_middle::traits::specialization_graph::OverlapMode;
|
2022-05-24 07:15:19 +00:00
|
|
|
use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
|
2023-10-15 11:40:17 +00:00
|
|
|
use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor};
|
|
|
|
use rustc_middle::ty::{self, Ty, TyCtxt};
|
2020-01-01 18:30:57 +00:00
|
|
|
use rustc_span::symbol::sym;
|
2024-03-12 13:26:30 +00:00
|
|
|
use rustc_span::{Span, DUMMY_SP};
|
2022-03-18 17:07:22 +00:00
|
|
|
use std::fmt::Debug;
|
2022-07-21 09:51:09 +00:00
|
|
|
use std::ops::ControlFlow;
|
2014-09-12 14:54:08 +00:00
|
|
|
|
2024-02-23 10:57:59 +00:00
|
|
|
use super::error_reporting::suggest_new_overflow_limit;
|
2024-05-01 21:22:39 +00:00
|
|
|
use super::ObligationCtxt;
|
2024-02-23 10:57:59 +00:00
|
|
|
|
2023-10-15 11:40:17 +00:00
|
|
|
/// Whether we do the orphan check relative to this crate or to some remote crate.
|
2017-11-29 18:50:26 +00:00
|
|
|
#[derive(Copy, Clone, Debug)]
|
2023-10-15 11:40:17 +00:00
|
|
|
pub enum InCrate {
|
|
|
|
Local { mode: OrphanCheckMode },
|
2017-11-22 21:01:51 +00:00
|
|
|
Remote,
|
2017-11-22 20:39:40 +00:00
|
|
|
}
|
|
|
|
|
2023-10-15 11:40:17 +00:00
|
|
|
#[derive(Copy, Clone, Debug)]
|
|
|
|
pub enum OrphanCheckMode {
|
|
|
|
/// Proper orphan check.
|
|
|
|
Proper,
|
|
|
|
/// Improper orphan check for backward compatibility.
|
|
|
|
///
|
|
|
|
/// In this mode, type params inside projections are considered to be covered
|
|
|
|
/// even if the projection may normalize to a type that doesn't actually cover
|
|
|
|
/// them. This is unsound. See also [#124559] and [#99554].
|
|
|
|
///
|
|
|
|
/// [#124559]: https://github.com/rust-lang/rust/issues/124559
|
|
|
|
/// [#99554]: https://github.com/rust-lang/rust/issues/99554
|
|
|
|
Compat,
|
|
|
|
}
|
|
|
|
|
2017-11-22 20:39:40 +00:00
|
|
|
#[derive(Debug, Copy, Clone)]
|
|
|
|
pub enum Conflict {
|
|
|
|
Upstream,
|
2020-02-08 18:14:50 +00:00
|
|
|
Downstream,
|
2017-11-22 20:39:40 +00:00
|
|
|
}
|
2015-03-30 21:46:34 +00:00
|
|
|
|
2017-07-23 13:30:47 +00:00
|
|
|
pub struct OverlapResult<'tcx> {
|
|
|
|
pub impl_header: ty::ImplHeader<'tcx>,
|
2023-11-24 18:10:30 +00:00
|
|
|
pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
|
2018-11-20 16:20:05 +00:00
|
|
|
|
2019-02-08 13:53:55 +00:00
|
|
|
/// `true` if the overlap might've been permitted before the shift
|
2018-11-20 16:20:05 +00:00
|
|
|
/// to universes.
|
|
|
|
pub involves_placeholder: bool,
|
2024-02-23 10:57:59 +00:00
|
|
|
|
|
|
|
/// Used in the new solver to suggest increasing the recursion limit.
|
|
|
|
pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
|
2018-11-20 16:20:05 +00:00
|
|
|
}
|
|
|
|
|
2024-02-22 23:20:45 +00:00
|
|
|
pub fn add_placeholder_note<G: EmissionGuarantee>(err: &mut Diag<'_, G>) {
|
2020-02-27 12:34:08 +00:00
|
|
|
err.note(
|
2018-11-20 16:20:05 +00:00
|
|
|
"this behavior recently changed as a result of a bug fix; \
|
2020-02-27 12:34:08 +00:00
|
|
|
see rust-lang/rust#56105 for details",
|
|
|
|
);
|
2017-07-23 13:30:47 +00:00
|
|
|
}
|
|
|
|
|
2024-02-23 10:57:59 +00:00
|
|
|
pub fn suggest_increasing_recursion_limit<'tcx, G: EmissionGuarantee>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
err: &mut Diag<'_, G>,
|
|
|
|
overflowing_predicates: &[ty::Predicate<'tcx>],
|
|
|
|
) {
|
|
|
|
for pred in overflowing_predicates {
|
|
|
|
err.note(format!("overflow evaluating the requirement `{}`", pred));
|
|
|
|
}
|
|
|
|
|
|
|
|
suggest_new_overflow_limit(tcx, err);
|
|
|
|
}
|
|
|
|
|
2023-05-23 16:56:25 +00:00
|
|
|
#[derive(Debug, Clone, Copy)]
|
|
|
|
enum TrackAmbiguityCauses {
|
|
|
|
Yes,
|
|
|
|
No,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl TrackAmbiguityCauses {
|
|
|
|
fn is_yes(self) -> bool {
|
|
|
|
match self {
|
|
|
|
TrackAmbiguityCauses::Yes => true,
|
|
|
|
TrackAmbiguityCauses::No => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-10-11 20:37:11 +00:00
|
|
|
/// If there are types that satisfy both impls, returns `Some`
|
2018-01-29 23:20:24 +00:00
|
|
|
/// with a suitably-freshened `ImplHeader` with those types
|
2024-02-12 06:39:32 +00:00
|
|
|
/// instantiated. Otherwise, returns `None`.
|
2022-10-11 20:37:11 +00:00
|
|
|
#[instrument(skip(tcx, skip_leak_check), level = "debug")]
|
2022-12-20 21:10:40 +00:00
|
|
|
pub fn overlapping_impls(
|
|
|
|
tcx: TyCtxt<'_>,
|
2018-01-29 23:20:24 +00:00
|
|
|
impl1_def_id: DefId,
|
|
|
|
impl2_def_id: DefId,
|
2020-01-24 20:57:01 +00:00
|
|
|
skip_leak_check: SkipLeakCheck,
|
2022-01-30 21:55:22 +00:00
|
|
|
overlap_mode: OverlapMode,
|
2022-12-20 21:10:40 +00:00
|
|
|
) -> Option<OverlapResult<'_>> {
|
2021-02-04 09:45:17 +00: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.
|
2023-03-12 00:59:54 +00:00
|
|
|
let drcx = DeepRejectCtxt { treat_obligation_params: TreatParams::AsCandidateKey };
|
2023-01-11 18:32:33 +00:00
|
|
|
let impl1_ref = tcx.impl_trait_ref(impl1_def_id);
|
|
|
|
let impl2_ref = tcx.impl_trait_ref(impl2_def_id);
|
2022-05-24 07:15:19 +00:00
|
|
|
let may_overlap = match (impl1_ref, impl2_ref) {
|
2023-11-13 11:27:15 +00:00
|
|
|
(Some(a), Some(b)) => drcx.args_may_unify(a.skip_binder().args, b.skip_binder().args),
|
2022-05-24 07:15:19 +00:00
|
|
|
(None, None) => {
|
2023-02-07 08:29:48 +00:00
|
|
|
let self_ty1 = tcx.type_of(impl1_def_id).skip_binder();
|
|
|
|
let self_ty2 = tcx.type_of(impl2_def_id).skip_binder();
|
2022-05-24 07:15:19 +00:00
|
|
|
drcx.types_may_unify(self_ty1, self_ty2)
|
2021-03-08 23:32:41 +00:00
|
|
|
}
|
2022-05-24 07:15:19 +00:00
|
|
|
_ => bug!("unexpected impls: {impl1_def_id:?} {impl2_def_id:?}"),
|
|
|
|
};
|
|
|
|
|
|
|
|
if !may_overlap {
|
2021-02-04 09:45:17 +00:00
|
|
|
// Some types involved are definitely different, so the impls couldn't possibly overlap.
|
|
|
|
debug!("overlapping_impls: fast_reject early-exit");
|
2022-10-11 20:37:11 +00:00
|
|
|
return None;
|
2021-02-04 09:45:17 +00:00
|
|
|
}
|
2014-10-09 21:19:50 +00:00
|
|
|
|
2023-05-23 16:56:25 +00:00
|
|
|
let _overlap_with_bad_diagnostics = overlap(
|
|
|
|
tcx,
|
|
|
|
TrackAmbiguityCauses::No,
|
|
|
|
skip_leak_check,
|
|
|
|
impl1_def_id,
|
|
|
|
impl2_def_id,
|
|
|
|
overlap_mode,
|
|
|
|
)?;
|
2018-01-26 22:21:43 +00:00
|
|
|
|
|
|
|
// In the case where we detect an error, run the check again, but
|
2022-03-30 19:14:15 +00:00
|
|
|
// this time tracking intercrate ambiguity causes for better
|
2018-01-26 22:21:43 +00:00
|
|
|
// diagnostics. (These take time and can lead to false errors.)
|
2023-05-23 16:56:25 +00:00
|
|
|
let overlap = overlap(
|
|
|
|
tcx,
|
|
|
|
TrackAmbiguityCauses::Yes,
|
|
|
|
skip_leak_check,
|
|
|
|
impl1_def_id,
|
|
|
|
impl2_def_id,
|
|
|
|
overlap_mode,
|
|
|
|
)
|
|
|
|
.unwrap();
|
|
|
|
Some(overlap)
|
2015-02-12 17:42:02 +00:00
|
|
|
}
|
|
|
|
|
2023-06-21 02:52:57 +00:00
|
|
|
fn fresh_impl_header<'tcx>(infcx: &InferCtxt<'tcx>, impl_def_id: DefId) -> ty::ImplHeader<'tcx> {
|
|
|
|
let tcx = infcx.tcx;
|
|
|
|
let impl_args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
|
2017-05-23 08:19:47 +00:00
|
|
|
|
2023-06-21 02:52:57 +00:00
|
|
|
ty::ImplHeader {
|
2017-07-03 18:19:51 +00:00
|
|
|
impl_def_id,
|
2023-06-21 02:52:57 +00:00
|
|
|
impl_args,
|
2023-07-11 21:35:29 +00:00
|
|
|
self_ty: tcx.type_of(impl_def_id).instantiate(tcx, impl_args),
|
|
|
|
trait_ref: tcx.impl_trait_ref(impl_def_id).map(|i| i.instantiate(tcx, impl_args)),
|
2023-06-22 18:17:13 +00:00
|
|
|
predicates: tcx
|
|
|
|
.predicates_of(impl_def_id)
|
2023-07-11 21:35:29 +00:00
|
|
|
.instantiate(tcx, impl_args)
|
2023-06-22 18:17:13 +00:00
|
|
|
.iter()
|
2023-08-24 19:22:24 +00:00
|
|
|
.map(|(c, _)| c.as_predicate())
|
2023-06-22 18:17:13 +00:00
|
|
|
.collect(),
|
2023-06-21 02:52:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn fresh_impl_header_normalized<'tcx>(
|
|
|
|
infcx: &InferCtxt<'tcx>,
|
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
|
|
|
impl_def_id: DefId,
|
|
|
|
) -> ty::ImplHeader<'tcx> {
|
|
|
|
let header = fresh_impl_header(infcx, impl_def_id);
|
2017-05-23 08:19:47 +00:00
|
|
|
|
2023-08-24 19:22:24 +00:00
|
|
|
let InferOk { value: mut header, obligations } =
|
2023-06-21 02:52:57 +00:00
|
|
|
infcx.at(&ObligationCause::dummy(), param_env).normalize(header);
|
2017-05-23 08:19:47 +00:00
|
|
|
|
2023-08-24 19:22:24 +00:00
|
|
|
header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
|
2017-05-23 08:19:47 +00:00
|
|
|
header
|
|
|
|
}
|
|
|
|
|
2015-12-01 19:26:47 +00:00
|
|
|
/// Can both impl `a` and impl `b` be satisfied by a common type (including
|
2019-02-08 13:53:55 +00:00
|
|
|
/// where-clauses)? If so, returns an `ImplHeader` that unifies the two impls.
|
2023-05-23 16:56:25 +00:00
|
|
|
#[instrument(level = "debug", skip(tcx))]
|
|
|
|
fn overlap<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
|
|
|
track_ambiguity_causes: TrackAmbiguityCauses,
|
2020-01-24 20:57:01 +00:00
|
|
|
skip_leak_check: SkipLeakCheck,
|
2022-01-21 13:50:42 +00:00
|
|
|
impl1_def_id: DefId,
|
|
|
|
impl2_def_id: DefId,
|
2022-01-30 21:55:22 +00:00
|
|
|
overlap_mode: OverlapMode,
|
2018-11-20 16:20:05 +00:00
|
|
|
) -> Option<OverlapResult<'tcx>> {
|
2022-01-22 21:16:11 +00:00
|
|
|
if overlap_mode.use_negative_impl() {
|
2023-06-14 02:18:30 +00:00
|
|
|
if impl_intersection_has_negative_obligation(tcx, impl1_def_id, impl2_def_id)
|
|
|
|
|| impl_intersection_has_negative_obligation(tcx, impl2_def_id, impl1_def_id)
|
2022-01-22 21:16:11 +00:00
|
|
|
{
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-05-23 16:56:25 +00:00
|
|
|
let infcx = tcx
|
|
|
|
.infer_ctxt()
|
|
|
|
.skip_leak_check(skip_leak_check.is_yes())
|
|
|
|
.intercrate(true)
|
2023-05-31 01:02:40 +00:00
|
|
|
.with_next_trait_solver(tcx.next_trait_solver_in_coherence())
|
2023-05-23 16:56:25 +00:00
|
|
|
.build();
|
2024-03-20 19:47:00 +00:00
|
|
|
let selcx = &mut SelectionContext::new(&infcx);
|
2023-05-23 16:56:25 +00:00
|
|
|
if track_ambiguity_causes.is_yes() {
|
|
|
|
selcx.enable_tracking_intercrate_ambiguity_causes();
|
|
|
|
}
|
|
|
|
|
2018-09-07 13:46:53 +00:00
|
|
|
// For the purposes of this check, we don't bring any placeholder
|
2017-05-23 08:19:47 +00: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 18:18:02 +00:00
|
|
|
let param_env = ty::ParamEnv::empty();
|
2017-05-23 08:19:47 +00:00
|
|
|
|
2023-06-21 02:52:57 +00:00
|
|
|
let impl1_header = fresh_impl_header_normalized(selcx.infcx, param_env, impl1_def_id);
|
|
|
|
let impl2_header = fresh_impl_header_normalized(selcx.infcx, param_env, impl2_def_id);
|
2015-03-30 21:46:34 +00:00
|
|
|
|
2023-06-14 02:18:30 +00:00
|
|
|
// Equate the headers to find their intersection (the general type, with infer vars,
|
|
|
|
// that may apply both impls).
|
2023-06-21 02:52:57 +00:00
|
|
|
let mut obligations =
|
|
|
|
equate_impl_headers(selcx.infcx, param_env, &impl1_header, &impl2_header)?;
|
2022-01-22 21:16:11 +00:00
|
|
|
debug!("overlap: unification check succeeded");
|
|
|
|
|
2023-09-20 19:41:07 +00:00
|
|
|
obligations.extend(
|
|
|
|
[&impl1_header.predicates, &impl2_header.predicates].into_iter().flatten().map(
|
|
|
|
|&predicate| Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, predicate),
|
|
|
|
),
|
|
|
|
);
|
2023-07-25 16:49:17 +00:00
|
|
|
|
2024-02-23 10:57:59 +00:00
|
|
|
let mut overflowing_predicates = Vec::new();
|
2023-09-21 06:56:23 +00:00
|
|
|
if overlap_mode.use_implicit_negative() {
|
2024-02-23 10:57:59 +00:00
|
|
|
match impl_intersection_has_impossible_obligation(selcx, &obligations) {
|
|
|
|
IntersectionHasImpossibleObligations::Yes => return None,
|
|
|
|
IntersectionHasImpossibleObligations::No { overflowing_predicates: p } => {
|
|
|
|
overflowing_predicates = p
|
|
|
|
}
|
2023-07-25 16:49:17 +00:00
|
|
|
}
|
2022-01-21 14:02:52 +00:00
|
|
|
}
|
|
|
|
|
2023-05-23 16:56:25 +00:00
|
|
|
// We toggle the `leak_check` by using `skip_leak_check` when constructing the
|
|
|
|
// inference context, so this may be a noop.
|
|
|
|
if infcx.leak_check(ty::UniverseIndex::ROOT, None).is_err() {
|
2022-02-21 09:40:41 +00:00
|
|
|
debug!("overlap: leak check failed");
|
|
|
|
return None;
|
2022-01-21 14:02:52 +00:00
|
|
|
}
|
|
|
|
|
2023-09-21 06:56:23 +00:00
|
|
|
let intercrate_ambiguity_causes = if !overlap_mode.use_implicit_negative() {
|
|
|
|
Default::default()
|
|
|
|
} else if infcx.next_trait_solver() {
|
2023-09-20 19:41:07 +00:00
|
|
|
compute_intercrate_ambiguity_causes(&infcx, &obligations)
|
|
|
|
} else {
|
|
|
|
selcx.take_intercrate_ambiguity_causes()
|
|
|
|
};
|
|
|
|
|
2022-01-21 14:02:52 +00:00
|
|
|
debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
|
2023-05-23 16:56:25 +00:00
|
|
|
let involves_placeholder = infcx
|
|
|
|
.inner
|
|
|
|
.borrow_mut()
|
|
|
|
.unwrap_region_constraints()
|
|
|
|
.data()
|
|
|
|
.constraints
|
|
|
|
.iter()
|
|
|
|
.any(|c| c.0.involves_placeholders());
|
2022-01-21 14:02:52 +00:00
|
|
|
|
2023-11-27 03:20:45 +00:00
|
|
|
let mut impl_header = infcx.resolve_vars_if_possible(impl1_header);
|
|
|
|
|
|
|
|
// Deeply normalize the impl header for diagnostics, ignoring any errors if this fails.
|
|
|
|
if infcx.next_trait_solver() {
|
|
|
|
impl_header = deeply_normalize_for_diagnostics(&infcx, param_env, impl_header);
|
|
|
|
}
|
|
|
|
|
2024-02-23 10:57:59 +00:00
|
|
|
Some(OverlapResult {
|
|
|
|
impl_header,
|
|
|
|
intercrate_ambiguity_causes,
|
|
|
|
involves_placeholder,
|
|
|
|
overflowing_predicates,
|
|
|
|
})
|
2022-01-21 14:02:52 +00:00
|
|
|
}
|
|
|
|
|
2023-03-15 13:00:15 +00:00
|
|
|
#[instrument(level = "debug", skip(infcx), ret)]
|
|
|
|
fn equate_impl_headers<'tcx>(
|
|
|
|
infcx: &InferCtxt<'tcx>,
|
2023-06-21 02:52:57 +00:00
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
2023-03-15 13:00:15 +00:00
|
|
|
impl1: &ty::ImplHeader<'tcx>,
|
|
|
|
impl2: &ty::ImplHeader<'tcx>,
|
2022-01-22 21:16:11 +00:00
|
|
|
) -> Option<PredicateObligations<'tcx>> {
|
2023-06-21 02:52:57 +00:00
|
|
|
let result =
|
|
|
|
match (impl1.trait_ref, impl2.trait_ref) {
|
|
|
|
(Some(impl1_ref), Some(impl2_ref)) => infcx
|
|
|
|
.at(&ObligationCause::dummy(), param_env)
|
|
|
|
.eq(DefineOpaqueTypes::Yes, impl1_ref, impl2_ref),
|
|
|
|
(None, None) => infcx.at(&ObligationCause::dummy(), param_env).eq(
|
|
|
|
DefineOpaqueTypes::Yes,
|
|
|
|
impl1.self_ty,
|
|
|
|
impl2.self_ty,
|
|
|
|
),
|
2023-11-21 13:31:40 +00:00
|
|
|
_ => bug!("equate_impl_headers given mismatched impl kinds"),
|
2023-06-21 02:52:57 +00:00
|
|
|
};
|
2023-03-15 13:00:15 +00:00
|
|
|
|
|
|
|
result.map(|infer_ok| infer_ok.obligations).ok()
|
2022-01-22 21:16:11 +00:00
|
|
|
}
|
|
|
|
|
2024-02-23 10:57:59 +00:00
|
|
|
/// The result of [fn impl_intersection_has_impossible_obligation].
|
|
|
|
enum IntersectionHasImpossibleObligations<'tcx> {
|
|
|
|
Yes,
|
|
|
|
No {
|
|
|
|
/// With `-Znext-solver=coherence`, some obligations may
|
|
|
|
/// fail if only the user increased the recursion limit.
|
|
|
|
///
|
|
|
|
/// We return those obligations here and mention them in the
|
|
|
|
/// error message.
|
|
|
|
overflowing_predicates: Vec<ty::Predicate<'tcx>>,
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
2023-06-14 02:18:30 +00:00
|
|
|
/// Check if both impls can be satisfied by a common type by considering whether
|
|
|
|
/// any of either impl's obligations is not known to hold.
|
|
|
|
///
|
|
|
|
/// For example, given these two impls:
|
|
|
|
/// `impl From<MyLocalType> for Box<dyn Error>` (in my crate)
|
|
|
|
/// `impl<E> From<E> for Box<dyn Error> where E: Error` (in libstd)
|
|
|
|
///
|
|
|
|
/// After replacing both impl headers with inference vars (which happens before
|
|
|
|
/// this function is called), we get:
|
|
|
|
/// `Box<dyn Error>: From<MyLocalType>`
|
|
|
|
/// `Box<dyn Error>: From<?E>`
|
|
|
|
///
|
|
|
|
/// This gives us `?E = MyLocalType`. We then certainly know that `MyLocalType: Error`
|
|
|
|
/// never holds in intercrate mode since a local impl does not exist, and a
|
|
|
|
/// downstream impl cannot be added -- therefore can consider the intersection
|
|
|
|
/// of the two impls above to be empty.
|
|
|
|
///
|
|
|
|
/// Importantly, this works even if there isn't a `impl !Error for MyLocalType`.
|
2023-09-20 19:41:07 +00:00
|
|
|
fn impl_intersection_has_impossible_obligation<'a, 'cx, 'tcx>(
|
2022-01-21 14:02:52 +00:00
|
|
|
selcx: &mut SelectionContext<'cx, 'tcx>,
|
2023-09-20 19:41:07 +00:00
|
|
|
obligations: &'a [PredicateObligation<'tcx>],
|
2024-02-23 10:57:59 +00:00
|
|
|
) -> IntersectionHasImpossibleObligations<'tcx> {
|
2022-11-25 23:31:28 +00:00
|
|
|
let infcx = selcx.infcx;
|
2023-06-14 02:18:30 +00:00
|
|
|
|
2024-02-16 17:56:15 +00:00
|
|
|
if infcx.next_trait_solver() {
|
2024-06-01 18:51:31 +00:00
|
|
|
let ocx = ObligationCtxt::new_with_diagnostics(infcx);
|
2024-05-01 21:22:39 +00:00
|
|
|
ocx.register_obligations(obligations.iter().cloned());
|
|
|
|
let errors_and_ambiguities = ocx.select_all_or_error();
|
2024-02-16 17:56:15 +00:00
|
|
|
// We only care about the obligations that are *definitely* true errors.
|
|
|
|
// Ambiguities do not prove the disjointness of two impls.
|
2024-05-01 21:22:39 +00:00
|
|
|
let (errors, ambiguities): (Vec<_>, Vec<_>) =
|
|
|
|
errors_and_ambiguities.into_iter().partition(|error| error.is_true_error());
|
|
|
|
|
2024-02-23 10:57:59 +00:00
|
|
|
if errors.is_empty() {
|
2024-05-01 21:22:39 +00:00
|
|
|
IntersectionHasImpossibleObligations::No {
|
|
|
|
overflowing_predicates: ambiguities
|
|
|
|
.into_iter()
|
|
|
|
.filter(|error| {
|
|
|
|
matches!(
|
|
|
|
error.code,
|
|
|
|
FulfillmentErrorCode::Ambiguity { overflow: Some(true) }
|
|
|
|
)
|
|
|
|
})
|
|
|
|
.map(|e| infcx.resolve_vars_if_possible(e.obligation.predicate))
|
|
|
|
.collect(),
|
|
|
|
}
|
2024-02-23 10:57:59 +00:00
|
|
|
} else {
|
|
|
|
IntersectionHasImpossibleObligations::Yes
|
|
|
|
}
|
2024-02-16 17:56:15 +00:00
|
|
|
} else {
|
2024-02-23 10:57:59 +00:00
|
|
|
for obligation in obligations {
|
|
|
|
// We use `evaluate_root_obligation` to correctly track intercrate
|
|
|
|
// ambiguity clauses.
|
|
|
|
let evaluation_result = selcx.evaluate_root_obligation(obligation);
|
|
|
|
|
|
|
|
match evaluation_result {
|
|
|
|
Ok(result) => {
|
|
|
|
if !result.may_apply() {
|
|
|
|
return IntersectionHasImpossibleObligations::Yes;
|
|
|
|
}
|
2024-02-23 18:07:42 +00:00
|
|
|
}
|
2024-02-23 10:57:59 +00:00
|
|
|
// If overflow occurs, we need to conservatively treat the goal as possibly holding,
|
|
|
|
// since there can be instantiations of this goal that don't overflow and result in
|
|
|
|
// success. While this isn't much of a problem in the old solver, since we treat overflow
|
|
|
|
// fatally, this still can be encountered: <https://github.com/rust-lang/rust/issues/105231>.
|
|
|
|
Err(_overflow) => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
IntersectionHasImpossibleObligations::No { overflowing_predicates: Vec::new() }
|
2024-02-16 17:56:15 +00:00
|
|
|
}
|
2015-02-12 17:42:02 +00:00
|
|
|
}
|
|
|
|
|
2023-06-14 02:18:30 +00:00
|
|
|
/// Check if both impls can be satisfied by a common type by considering whether
|
|
|
|
/// any of first impl's obligations is known not to hold *via a negative predicate*.
|
|
|
|
///
|
|
|
|
/// For example, given these two impls:
|
|
|
|
/// `struct MyCustomBox<T: ?Sized>(Box<T>);`
|
|
|
|
/// `impl From<&str> for MyCustomBox<dyn Error>` (in my crate)
|
|
|
|
/// `impl<E> From<E> for MyCustomBox<dyn Error> where E: Error` (in my crate)
|
|
|
|
///
|
|
|
|
/// After replacing the second impl's header with inference vars, we get:
|
|
|
|
/// `MyCustomBox<dyn Error>: From<&str>`
|
|
|
|
/// `MyCustomBox<dyn Error>: From<?E>`
|
|
|
|
///
|
|
|
|
/// This gives us `?E = &str`. We then try to prove the first impl's predicates
|
|
|
|
/// after negating, giving us `&str: !Error`. This is a negative impl provided by
|
|
|
|
/// libstd, and therefore we can guarantee for certain that libstd will never add
|
|
|
|
/// a positive impl for `&str: Error` (without it being a breaking change).
|
|
|
|
fn impl_intersection_has_negative_obligation(
|
|
|
|
tcx: TyCtxt<'_>,
|
|
|
|
impl1_def_id: DefId,
|
|
|
|
impl2_def_id: DefId,
|
|
|
|
) -> bool {
|
2022-02-04 01:40:29 +00:00
|
|
|
debug!("negative_impl(impl1_def_id={:?}, impl2_def_id={:?})", impl1_def_id, impl2_def_id);
|
2022-01-21 15:53:50 +00:00
|
|
|
|
2023-11-19 19:19:51 +00:00
|
|
|
// N.B. We need to unify impl headers *with* intercrate mode, even if proving negative predicates
|
|
|
|
// do not need intercrate mode enabled.
|
2023-06-21 03:44:19 +00:00
|
|
|
let ref infcx = tcx.infer_ctxt().intercrate(true).with_next_trait_solver(true).build();
|
2023-11-17 03:00:38 +00:00
|
|
|
let root_universe = infcx.universe();
|
|
|
|
assert_eq!(root_universe, ty::UniverseIndex::ROOT);
|
2022-09-20 03:03:59 +00:00
|
|
|
|
2023-06-21 03:17:25 +00:00
|
|
|
let impl1_header = fresh_impl_header(infcx, impl1_def_id);
|
|
|
|
let param_env =
|
|
|
|
ty::EarlyBinder::bind(tcx.param_env(impl1_def_id)).instantiate(tcx, impl1_header.impl_args);
|
|
|
|
|
|
|
|
let impl2_header = fresh_impl_header(infcx, impl2_def_id);
|
|
|
|
|
|
|
|
// Equate the headers to find their intersection (the general type, with infer vars,
|
|
|
|
// that may apply both impls).
|
2023-11-16 22:50:59 +00:00
|
|
|
let Some(equate_obligations) =
|
2023-06-21 03:17:25 +00:00
|
|
|
equate_impl_headers(infcx, param_env, &impl1_header, &impl2_header)
|
2022-03-24 15:27:09 +00:00
|
|
|
else {
|
2023-06-14 02:18:30 +00:00
|
|
|
return false;
|
2022-03-24 15:27:09 +00:00
|
|
|
};
|
2022-03-18 17:07:22 +00:00
|
|
|
|
2023-11-16 22:50:59 +00:00
|
|
|
// FIXME(with_negative_coherence): the infcx has constraints from equating
|
|
|
|
// the impl headers. We should use these constraints as assumptions, not as
|
|
|
|
// requirements, when proving the negated where clauses below.
|
|
|
|
drop(equate_obligations);
|
|
|
|
drop(infcx.take_registered_region_obligations());
|
|
|
|
drop(infcx.take_and_reset_region_constraints());
|
|
|
|
|
2023-11-20 18:39:44 +00:00
|
|
|
plug_infer_with_placeholders(
|
|
|
|
infcx,
|
|
|
|
root_universe,
|
|
|
|
(impl1_header.impl_args, impl2_header.impl_args),
|
|
|
|
);
|
|
|
|
let param_env = infcx.resolve_vars_if_possible(param_env);
|
|
|
|
|
2023-10-17 23:04:06 +00:00
|
|
|
util::elaborate(tcx, tcx.predicates_of(impl2_def_id).instantiate(tcx, impl2_header.impl_args))
|
|
|
|
.any(|(clause, _)| try_prove_negated_where_clause(infcx, clause, param_env))
|
2022-03-18 17:07:22 +00:00
|
|
|
}
|
|
|
|
|
2023-06-21 03:17:25 +00:00
|
|
|
fn plug_infer_with_placeholders<'tcx>(
|
|
|
|
infcx: &InferCtxt<'tcx>,
|
|
|
|
universe: ty::UniverseIndex,
|
|
|
|
value: impl TypeVisitable<TyCtxt<'tcx>>,
|
|
|
|
) {
|
|
|
|
struct PlugInferWithPlaceholder<'a, 'tcx> {
|
|
|
|
infcx: &'a InferCtxt<'tcx>,
|
|
|
|
universe: ty::UniverseIndex,
|
|
|
|
var: ty::BoundVar,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'tcx> PlugInferWithPlaceholder<'_, 'tcx> {
|
|
|
|
fn next_var(&mut self) -> ty::BoundVar {
|
|
|
|
let var = self.var;
|
|
|
|
self.var = self.var + 1;
|
|
|
|
var
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for PlugInferWithPlaceholder<'_, 'tcx> {
|
2024-02-24 22:22:28 +00:00
|
|
|
fn visit_ty(&mut self, ty: Ty<'tcx>) {
|
2023-06-21 03:17:25 +00:00
|
|
|
let ty = self.infcx.shallow_resolve(ty);
|
|
|
|
if ty.is_ty_var() {
|
|
|
|
let Ok(InferOk { value: (), obligations }) =
|
|
|
|
self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
|
2024-02-21 11:42:39 +00:00
|
|
|
// Comparing against a type variable never registers hidden types anyway
|
|
|
|
DefineOpaqueTypes::Yes,
|
2023-06-21 03:17:25 +00:00
|
|
|
ty,
|
|
|
|
Ty::new_placeholder(
|
|
|
|
self.infcx.tcx,
|
|
|
|
ty::Placeholder {
|
|
|
|
universe: self.universe,
|
|
|
|
bound: ty::BoundTy {
|
|
|
|
var: self.next_var(),
|
|
|
|
kind: ty::BoundTyKind::Anon,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
),
|
|
|
|
)
|
|
|
|
else {
|
2023-12-15 03:19:46 +00:00
|
|
|
bug!("we always expect to be able to plug an infer var with placeholder")
|
2023-06-21 03:17:25 +00:00
|
|
|
};
|
|
|
|
assert_eq!(obligations, &[]);
|
|
|
|
} else {
|
2024-02-24 22:22:28 +00:00
|
|
|
ty.super_visit_with(self);
|
2023-06-21 03:17:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-24 22:22:28 +00:00
|
|
|
fn visit_const(&mut self, ct: ty::Const<'tcx>) {
|
2024-04-06 06:05:17 +00:00
|
|
|
let ct = self.infcx.shallow_resolve_const(ct);
|
2023-06-21 03:17:25 +00:00
|
|
|
if ct.is_ct_infer() {
|
|
|
|
let Ok(InferOk { value: (), obligations }) =
|
|
|
|
self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
|
2024-02-21 11:42:39 +00:00
|
|
|
// The types of the constants are the same, so there is no hidden type
|
|
|
|
// registration happening anyway.
|
|
|
|
DefineOpaqueTypes::Yes,
|
2023-06-21 03:17:25 +00:00
|
|
|
ct,
|
|
|
|
ty::Const::new_placeholder(
|
|
|
|
self.infcx.tcx,
|
|
|
|
ty::Placeholder { universe: self.universe, bound: self.next_var() },
|
|
|
|
),
|
|
|
|
)
|
|
|
|
else {
|
2023-12-15 03:19:46 +00:00
|
|
|
bug!("we always expect to be able to plug an infer var with placeholder")
|
2023-06-21 03:17:25 +00:00
|
|
|
};
|
|
|
|
assert_eq!(obligations, &[]);
|
|
|
|
} else {
|
2024-02-24 22:22:28 +00:00
|
|
|
ct.super_visit_with(self);
|
2023-06-21 03:17:25 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-02-24 22:22:28 +00:00
|
|
|
fn visit_region(&mut self, r: ty::Region<'tcx>) {
|
2023-06-21 03:17:25 +00:00
|
|
|
if let ty::ReVar(vid) = *r {
|
|
|
|
let r = self
|
|
|
|
.infcx
|
|
|
|
.inner
|
|
|
|
.borrow_mut()
|
|
|
|
.unwrap_region_constraints()
|
|
|
|
.opportunistic_resolve_var(self.infcx.tcx, vid);
|
|
|
|
if r.is_var() {
|
|
|
|
let Ok(InferOk { value: (), obligations }) =
|
|
|
|
self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
|
2024-02-21 11:42:39 +00:00
|
|
|
// Lifetimes don't contain opaque types (or any types for that matter).
|
|
|
|
DefineOpaqueTypes::Yes,
|
2023-06-21 03:17:25 +00:00
|
|
|
r,
|
|
|
|
ty::Region::new_placeholder(
|
|
|
|
self.infcx.tcx,
|
|
|
|
ty::Placeholder {
|
|
|
|
universe: self.universe,
|
|
|
|
bound: ty::BoundRegion {
|
|
|
|
var: self.next_var(),
|
|
|
|
kind: ty::BoundRegionKind::BrAnon,
|
|
|
|
},
|
|
|
|
},
|
|
|
|
),
|
|
|
|
)
|
|
|
|
else {
|
2023-12-15 03:19:46 +00:00
|
|
|
bug!("we always expect to be able to plug an infer var with placeholder")
|
2023-06-21 03:17:25 +00:00
|
|
|
};
|
|
|
|
assert_eq!(obligations, &[]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-03 14:49:59 +00:00
|
|
|
value.visit_with(&mut PlugInferWithPlaceholder { infcx, universe, var: ty::BoundVar::ZERO });
|
2023-06-21 03:17:25 +00:00
|
|
|
}
|
|
|
|
|
2023-10-17 23:04:06 +00:00
|
|
|
fn try_prove_negated_where_clause<'tcx>(
|
|
|
|
root_infcx: &InferCtxt<'tcx>,
|
|
|
|
clause: ty::Clause<'tcx>,
|
|
|
|
param_env: ty::ParamEnv<'tcx>,
|
2022-03-17 15:09:00 +00:00
|
|
|
) -> bool {
|
2023-10-17 23:04:06 +00:00
|
|
|
let Some(negative_predicate) = clause.as_predicate().flip_polarity(root_infcx.tcx) else {
|
2022-03-17 17:55:16 +00:00
|
|
|
return false;
|
|
|
|
};
|
2022-02-10 19:38:27 +00:00
|
|
|
|
2023-11-19 19:19:51 +00:00
|
|
|
// N.B. We don't need to use intercrate mode here because we're trying to prove
|
|
|
|
// the *existence* of a negative goal, not the non-existence of a positive goal.
|
|
|
|
// Without this, we over-eagerly register coherence ambiguity candidates when
|
|
|
|
// impl candidates do exist.
|
|
|
|
let ref infcx = root_infcx.fork_with_intercrate(false);
|
2024-05-01 21:22:39 +00:00
|
|
|
let ocx = ObligationCtxt::new(infcx);
|
|
|
|
ocx.register_obligation(Obligation::new(
|
|
|
|
infcx.tcx,
|
|
|
|
ObligationCause::dummy(),
|
|
|
|
param_env,
|
|
|
|
negative_predicate,
|
|
|
|
));
|
|
|
|
if !ocx.select_all_or_error().is_empty() {
|
2022-03-17 17:55:16 +00:00
|
|
|
return false;
|
|
|
|
}
|
2022-03-17 14:26:45 +00:00
|
|
|
|
2023-10-17 23:04:06 +00:00
|
|
|
// FIXME: We could use the assumed_wf_types from both impls, I think,
|
|
|
|
// if that wasn't implemented just for LocalDefId, and we'd need to do
|
|
|
|
// the normalization ourselves since this is totally fallible...
|
|
|
|
let outlives_env = OutlivesEnvironment::new(param_env);
|
2024-05-01 21:22:39 +00:00
|
|
|
let errors = ocx.resolve_regions(&outlives_env);
|
2023-10-17 23:04:06 +00:00
|
|
|
if !errors.is_empty() {
|
2023-06-27 21:13:39 +00:00
|
|
|
return false;
|
2023-10-17 23:04:06 +00:00
|
|
|
}
|
2023-06-27 21:13:39 +00:00
|
|
|
|
2023-10-17 23:04:06 +00:00
|
|
|
true
|
2022-01-21 13:53:17 +00:00
|
|
|
}
|
|
|
|
|
2022-07-20 12:32:58 +00:00
|
|
|
/// Returns whether all impls which would apply to the `trait_ref`
|
|
|
|
/// e.g. `Ty: Trait<Arg>` are already known in the local crate.
|
|
|
|
///
|
|
|
|
/// This both checks whether any downstream or sibling crates could
|
|
|
|
/// implement it and whether an upstream crate can add this impl
|
|
|
|
/// without breaking backwards compatibility.
|
2024-05-02 15:44:05 +00:00
|
|
|
#[instrument(level = "debug", skip(infcx, lazily_normalize_ty), ret)]
|
2023-08-04 10:17:28 +00:00
|
|
|
pub fn trait_ref_is_knowable<'tcx, E: Debug>(
|
2024-05-02 15:44:05 +00:00
|
|
|
infcx: &InferCtxt<'tcx>,
|
2019-06-11 21:11:55 +00:00
|
|
|
trait_ref: ty::TraitRef<'tcx>,
|
2023-08-04 10:17:28 +00:00
|
|
|
mut lazily_normalize_ty: impl FnMut(Ty<'tcx>) -> Result<Ty<'tcx>, E>,
|
|
|
|
) -> Result<Result<(), Conflict>, E> {
|
2024-05-02 15:44:05 +00:00
|
|
|
if orphan_check_trait_ref(infcx, trait_ref, InCrate::Remote, &mut lazily_normalize_ty)?.is_ok()
|
|
|
|
{
|
2017-11-22 20:39:40 +00:00
|
|
|
// A downstream or cousin crate is allowed to implement some
|
2024-02-12 06:39:32 +00:00
|
|
|
// generic parameters of this trait-ref.
|
2023-08-04 10:17:28 +00:00
|
|
|
return Ok(Err(Conflict::Downstream));
|
2017-11-28 12:52:34 +00:00
|
|
|
}
|
|
|
|
|
2024-05-02 15:44:05 +00:00
|
|
|
if trait_ref_is_local_or_fundamental(infcx.tcx, trait_ref) {
|
2017-11-22 20:39:40 +00:00
|
|
|
// This is a local or fundamental trait, so future-compatibility
|
|
|
|
// is no concern. We know that downstream/cousin crates are not
|
2024-02-12 06:39:32 +00:00
|
|
|
// allowed to implement a generic parameter of this trait ref,
|
|
|
|
// which means impls could only come from dependencies of this
|
|
|
|
// crate, which we already know about.
|
2023-08-04 10:17:28 +00:00
|
|
|
return Ok(Ok(()));
|
2017-11-22 20:39:40 +00:00
|
|
|
}
|
2017-11-22 21:01:51 +00:00
|
|
|
|
2017-11-22 20:39:40 +00:00
|
|
|
// This is a remote non-fundamental trait, so if another crate
|
2024-02-12 06:39:32 +00:00
|
|
|
// can be the "final owner" of the generic parameters of this trait-ref,
|
2017-11-22 20:39:40 +00:00
|
|
|
// 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.
|
2023-10-15 11:40:17 +00:00
|
|
|
if orphan_check_trait_ref(
|
2024-05-02 15:44:05 +00:00
|
|
|
infcx,
|
2023-10-15 11:40:17 +00:00
|
|
|
trait_ref,
|
|
|
|
InCrate::Local { mode: OrphanCheckMode::Proper },
|
|
|
|
&mut lazily_normalize_ty,
|
|
|
|
)?
|
|
|
|
.is_ok()
|
|
|
|
{
|
2023-08-04 10:17:28 +00:00
|
|
|
Ok(Ok(()))
|
2017-11-22 20:39:40 +00:00
|
|
|
} else {
|
2023-08-04 10:17:28 +00:00
|
|
|
Ok(Err(Conflict::Upstream))
|
2015-03-30 21:46:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-06-13 21:48:52 +00:00
|
|
|
pub fn trait_ref_is_local_or_fundamental<'tcx>(
|
|
|
|
tcx: TyCtxt<'tcx>,
|
2019-06-11 21:11:55 +00:00
|
|
|
trait_ref: ty::TraitRef<'tcx>,
|
|
|
|
) -> bool {
|
2023-10-15 11:40:17 +00:00
|
|
|
trait_ref.def_id.is_local() || tcx.has_attr(trait_ref.def_id, sym::fundamental)
|
2017-08-28 20:50:41 +00:00
|
|
|
}
|
|
|
|
|
2024-02-13 23:57:43 +00:00
|
|
|
#[derive(Debug, Copy, Clone)]
|
|
|
|
pub enum IsFirstInputType {
|
|
|
|
No,
|
|
|
|
Yes,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<bool> for IsFirstInputType {
|
|
|
|
fn from(b: bool) -> IsFirstInputType {
|
|
|
|
match b {
|
|
|
|
false => IsFirstInputType::No,
|
|
|
|
true => IsFirstInputType::Yes,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-17 09:39:35 +00:00
|
|
|
#[derive(Debug)]
|
2023-10-15 11:40:17 +00:00
|
|
|
pub enum OrphanCheckErr<'tcx, T> {
|
2024-02-13 23:57:43 +00:00
|
|
|
NonLocalInputType(Vec<(Ty<'tcx>, IsFirstInputType)>),
|
2023-10-15 11:40:17 +00:00
|
|
|
UncoveredTyParams(UncoveredTyParams<'tcx, T>),
|
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 08:30:51 +00:00
|
|
|
}
|
|
|
|
|
2023-10-15 11:40:17 +00:00
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct UncoveredTyParams<'tcx, T> {
|
|
|
|
pub uncovered: T,
|
|
|
|
pub local_ty: Option<Ty<'tcx>>,
|
2015-03-30 21:46:34 +00:00
|
|
|
}
|
|
|
|
|
2019-02-08 13:53:55 +00:00
|
|
|
/// Checks whether a trait-ref is potentially implementable by a crate.
|
2017-11-29 18:50:26 +00:00
|
|
|
///
|
|
|
|
/// The current rule is that a trait-ref orphan checks in a crate C:
|
|
|
|
///
|
2024-02-12 06:39:32 +00:00
|
|
|
/// 1. Order the parameters in the trait-ref in generic parameters order
|
|
|
|
/// - Self first, others linearly (e.g., `<U as Foo<V, W>>` is U < V < W).
|
2017-11-29 18:50:26 +00: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 18:50:26 +00: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 21:18:06 +00: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.
|
2022-05-24 07:15:19 +00:00
|
|
|
/// - while `impl<T> Trait<LocalType> for Box<T>` results in an error, as `T` is
|
2020-07-20 21:18:06 +00:00
|
|
|
/// reachable through the fundamental type `Box`.
|
2017-11-29 18:50:26 +00: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 18:50:26 +00: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 14:56:50 +00:00
|
|
|
/// the second occurrence of `T` is not a subtree of *any* local type.
|
2017-11-29 18:50:26 +00: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 18:50:26 +00: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.
|
|
|
|
///
|
2023-10-15 11:40:17 +00:00
|
|
|
/// In InCrate::Local mode the orphan check succeeds if the current crate
|
|
|
|
/// is definitely allowed to implement the given trait (no false positives).
|
|
|
|
///
|
2017-11-29 18:50:26 +00:00
|
|
|
/// 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
|
2022-04-15 22:04:34 +00:00
|
|
|
/// ```ignore (illustrative)
|
2017-11-29 18:50:26 +00:00
|
|
|
/// impl<T> IntoIterator for Vec<T>
|
|
|
|
/// impl<T: Iterator> IntoIterator for T
|
|
|
|
/// ```
|
2017-12-05 13:43:37 +00:00
|
|
|
/// We need to be able to prove that `Vec<$0>: !Iterator` for every type $0.
|
2017-11-29 18:50:26 +00: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.
|
|
|
|
///
|
2023-10-15 11:40:17 +00:00
|
|
|
/// In InCrate::Remote mode the orphan check succeeds if a foreign crate
|
|
|
|
/// *could* implement the given trait (no false negatives).
|
|
|
|
///
|
2020-05-01 20:28:15 +00:00
|
|
|
/// 3. For non-`#[fundamental]` traits, they guarantee that parent crates can
|
2017-11-29 18:50:26 +00: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 20:28:15 +00:00
|
|
|
/// non-local-non-`#[fundamental]` only if there's a local key parameter as per (2).
|
2017-11-29 18:50:26 +00:00
|
|
|
///
|
|
|
|
/// Because we never perform negative reasoning generically (coherence does
|
|
|
|
/// not involve type parameters), this can be interpreted as doing the full
|
2024-02-12 06:39:32 +00:00
|
|
|
/// orphan check (using InCrate::Local mode), instantiating non-local known
|
2017-11-29 18:50:26 +00:00
|
|
|
/// 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.
|
2024-05-02 15:44:05 +00:00
|
|
|
#[instrument(level = "trace", skip(infcx, lazily_normalize_ty), ret)]
|
2023-10-15 11:40:17 +00:00
|
|
|
pub fn orphan_check_trait_ref<'tcx, E: Debug>(
|
2024-05-02 15:44:05 +00:00
|
|
|
infcx: &InferCtxt<'tcx>,
|
2019-06-11 21:11:55 +00:00
|
|
|
trait_ref: ty::TraitRef<'tcx>,
|
|
|
|
in_crate: InCrate,
|
2023-08-04 10:17:28 +00:00
|
|
|
lazily_normalize_ty: impl FnMut(Ty<'tcx>) -> Result<Ty<'tcx>, E>,
|
2023-10-15 11:40:17 +00:00
|
|
|
) -> Result<Result<(), OrphanCheckErr<'tcx, Ty<'tcx>>>, E> {
|
2024-05-02 15:44:05 +00:00
|
|
|
if trait_ref.has_param() {
|
|
|
|
bug!("orphan check only expects inference variables: {trait_ref:?}");
|
2017-11-29 18:50:26 +00:00
|
|
|
}
|
|
|
|
|
2024-05-02 15:44:05 +00:00
|
|
|
let mut checker = OrphanChecker::new(infcx, in_crate, lazily_normalize_ty);
|
2023-08-04 10:17:28 +00:00
|
|
|
Ok(match trait_ref.visit_with(&mut checker) {
|
2022-07-21 09:51:09 +00:00
|
|
|
ControlFlow::Continue(()) => Err(OrphanCheckErr::NonLocalInputType(checker.non_local_tys)),
|
2023-10-15 11:40:17 +00:00
|
|
|
ControlFlow::Break(residual) => match residual {
|
|
|
|
OrphanCheckEarlyExit::NormalizationFailure(err) => return Err(err),
|
|
|
|
OrphanCheckEarlyExit::UncoveredTyParam(ty) => {
|
2024-05-02 15:44:05 +00:00
|
|
|
// Does there exist some local type after the `ParamTy`.
|
|
|
|
checker.search_first_local_ty = true;
|
|
|
|
let local_ty = match trait_ref.visit_with(&mut checker).break_value() {
|
|
|
|
Some(OrphanCheckEarlyExit::LocalTy(local_ty)) => Some(local_ty),
|
|
|
|
_ => None,
|
|
|
|
};
|
2023-10-15 11:40:17 +00:00
|
|
|
Err(OrphanCheckErr::UncoveredTyParams(UncoveredTyParams {
|
|
|
|
uncovered: ty,
|
2024-05-02 15:44:05 +00:00
|
|
|
local_ty,
|
2023-10-15 11:40:17 +00:00
|
|
|
}))
|
2020-03-20 03:28:17 +00:00
|
|
|
}
|
2023-10-15 11:40:17 +00:00
|
|
|
OrphanCheckEarlyExit::LocalTy(_) => Ok(()),
|
|
|
|
},
|
2023-08-04 10:17:28 +00:00
|
|
|
})
|
2015-03-30 21:46:34 +00:00
|
|
|
}
|
|
|
|
|
2024-05-02 15:44:05 +00:00
|
|
|
struct OrphanChecker<'a, 'tcx, F> {
|
|
|
|
infcx: &'a InferCtxt<'tcx>,
|
2021-12-14 09:44:49 +00:00
|
|
|
in_crate: InCrate,
|
2022-07-21 09:51:09 +00:00
|
|
|
in_self_ty: bool,
|
2023-08-04 10:17:28 +00:00
|
|
|
lazily_normalize_ty: F,
|
2023-10-15 11:40:17 +00:00
|
|
|
/// Ignore orphan check failures and exclusively search for the first local type.
|
2022-07-21 09:51:09 +00:00
|
|
|
search_first_local_ty: bool,
|
2024-02-13 23:57:43 +00:00
|
|
|
non_local_tys: Vec<(Ty<'tcx>, IsFirstInputType)>,
|
2022-07-21 09:51:09 +00:00
|
|
|
}
|
|
|
|
|
2024-05-02 15:44:05 +00:00
|
|
|
impl<'a, 'tcx, F, E> OrphanChecker<'a, 'tcx, F>
|
2023-08-04 10:17:28 +00:00
|
|
|
where
|
|
|
|
F: FnOnce(Ty<'tcx>) -> Result<Ty<'tcx>, E>,
|
|
|
|
{
|
2024-05-02 15:44:05 +00:00
|
|
|
fn new(infcx: &'a InferCtxt<'tcx>, in_crate: InCrate, lazily_normalize_ty: F) -> Self {
|
2022-07-21 09:51:09 +00:00
|
|
|
OrphanChecker {
|
2024-05-02 15:44:05 +00:00
|
|
|
infcx,
|
2022-07-21 09:51:09 +00:00
|
|
|
in_crate,
|
|
|
|
in_self_ty: true,
|
2023-08-04 10:17:28 +00:00
|
|
|
lazily_normalize_ty,
|
2022-07-21 09:51:09 +00:00
|
|
|
search_first_local_ty: false,
|
|
|
|
non_local_tys: Vec::new(),
|
2020-07-17 19:40:47 +00:00
|
|
|
}
|
2019-10-13 18:25:30 +00:00
|
|
|
}
|
2015-03-30 21:46:34 +00:00
|
|
|
|
2023-08-04 10:17:28 +00:00
|
|
|
fn found_non_local_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<OrphanCheckEarlyExit<'tcx, E>> {
|
2024-02-13 23:57:43 +00:00
|
|
|
self.non_local_tys.push((t, self.in_self_ty.into()));
|
2023-01-18 07:17:13 +00:00
|
|
|
ControlFlow::Continue(())
|
2022-07-21 09:51:09 +00:00
|
|
|
}
|
2020-03-20 03:28:17 +00:00
|
|
|
|
2023-10-15 11:40:17 +00:00
|
|
|
fn found_uncovered_ty_param(
|
|
|
|
&mut self,
|
|
|
|
ty: Ty<'tcx>,
|
|
|
|
) -> ControlFlow<OrphanCheckEarlyExit<'tcx, E>> {
|
2022-07-21 09:51:09 +00:00
|
|
|
if self.search_first_local_ty {
|
2023-10-15 11:40:17 +00:00
|
|
|
return ControlFlow::Continue(());
|
2020-03-20 03:28:17 +00:00
|
|
|
}
|
2023-10-15 11:40:17 +00:00
|
|
|
|
|
|
|
ControlFlow::Break(OrphanCheckEarlyExit::UncoveredTyParam(ty))
|
2022-07-21 09:51:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn def_id_is_local(&mut self, def_id: DefId) -> bool {
|
|
|
|
match self.in_crate {
|
2023-10-15 11:40:17 +00:00
|
|
|
InCrate::Local { .. } => def_id.is_local(),
|
2022-07-21 09:51:09 +00:00
|
|
|
InCrate::Remote => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2020-03-20 03:28:17 +00:00
|
|
|
|
2023-08-04 10:17:28 +00:00
|
|
|
enum OrphanCheckEarlyExit<'tcx, E> {
|
|
|
|
NormalizationFailure(E),
|
2023-10-15 11:40:17 +00:00
|
|
|
UncoveredTyParam(Ty<'tcx>),
|
2022-07-21 09:51:09 +00:00
|
|
|
LocalTy(Ty<'tcx>),
|
2015-03-30 21:46:34 +00:00
|
|
|
}
|
|
|
|
|
2024-05-02 15:44:05 +00:00
|
|
|
impl<'a, 'tcx, F, E> TypeVisitor<TyCtxt<'tcx>> for OrphanChecker<'a, 'tcx, F>
|
2023-08-04 10:17:28 +00:00
|
|
|
where
|
|
|
|
F: FnMut(Ty<'tcx>) -> Result<Ty<'tcx>, E>,
|
|
|
|
{
|
2024-02-24 22:22:28 +00:00
|
|
|
type Result = ControlFlow<OrphanCheckEarlyExit<'tcx, E>>;
|
2023-10-15 11:40:17 +00:00
|
|
|
|
2024-02-24 22:22:28 +00:00
|
|
|
fn visit_region(&mut self, _r: ty::Region<'tcx>) -> Self::Result {
|
2023-01-18 07:17:13 +00:00
|
|
|
ControlFlow::Continue(())
|
2017-11-22 20:39:40 +00:00
|
|
|
}
|
|
|
|
|
2024-02-24 22:22:28 +00:00
|
|
|
fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
|
2024-05-02 15:44:05 +00:00
|
|
|
let ty = self.infcx.shallow_resolve(ty);
|
2023-08-04 10:17:28 +00:00
|
|
|
let ty = match (self.lazily_normalize_ty)(ty) {
|
2023-10-15 11:40:17 +00:00
|
|
|
Ok(norm_ty) if norm_ty.is_ty_var() => ty,
|
|
|
|
Ok(norm_ty) => norm_ty,
|
2023-08-04 10:17:28 +00:00
|
|
|
Err(err) => return ControlFlow::Break(OrphanCheckEarlyExit::NormalizationFailure(err)),
|
|
|
|
};
|
|
|
|
|
2022-07-21 09:51:09 +00:00
|
|
|
let result = match *ty.kind() {
|
|
|
|
ty::Bool
|
|
|
|
| ty::Char
|
|
|
|
| ty::Int(..)
|
|
|
|
| ty::Uint(..)
|
|
|
|
| ty::Float(..)
|
|
|
|
| ty::Str
|
|
|
|
| ty::FnDef(..)
|
2023-02-02 13:57:36 +00:00
|
|
|
| ty::Pat(..)
|
2022-07-21 09:51:09 +00:00
|
|
|
| ty::FnPtr(_)
|
|
|
|
| ty::Array(..)
|
|
|
|
| ty::Slice(..)
|
|
|
|
| ty::RawPtr(..)
|
|
|
|
| ty::Never
|
2023-10-15 11:40:17 +00:00
|
|
|
| ty::Tuple(..) => self.found_non_local_ty(ty),
|
|
|
|
|
|
|
|
ty::Param(..) => bug!("unexpected ty param"),
|
|
|
|
|
|
|
|
ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) => {
|
|
|
|
match self.in_crate {
|
|
|
|
InCrate::Local { .. } => self.found_uncovered_ty_param(ty),
|
|
|
|
// The inference variable might be unified with a local
|
|
|
|
// type in that remote crate.
|
|
|
|
InCrate::Remote => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
|
|
|
|
}
|
2023-03-07 12:03:11 +00:00
|
|
|
}
|
2022-07-21 09:51:09 +00:00
|
|
|
|
2024-06-01 21:44:59 +00:00
|
|
|
// A rigid alias may normalize to anything.
|
|
|
|
// * If it references an infer var, placeholder or bound ty, it may
|
|
|
|
// normalize to that, so we have to treat it as an uncovered ty param.
|
|
|
|
// * Otherwise it may normalize to any non-type-generic type
|
|
|
|
// be it local or non-local.
|
|
|
|
ty::Alias(kind, _) => {
|
2023-10-15 11:40:17 +00:00
|
|
|
if ty.has_type_flags(
|
|
|
|
ty::TypeFlags::HAS_TY_PLACEHOLDER
|
|
|
|
| ty::TypeFlags::HAS_TY_BOUND
|
|
|
|
| ty::TypeFlags::HAS_TY_INFER,
|
|
|
|
) {
|
|
|
|
match self.in_crate {
|
|
|
|
InCrate::Local { mode } => match kind {
|
|
|
|
ty::Projection if let OrphanCheckMode::Compat = mode => {
|
|
|
|
ControlFlow::Continue(())
|
|
|
|
}
|
|
|
|
_ => self.found_uncovered_ty_param(ty),
|
|
|
|
},
|
|
|
|
InCrate::Remote => {
|
|
|
|
// The inference variable might be unified with a local
|
|
|
|
// type in that remote crate.
|
|
|
|
ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2024-06-01 21:44:59 +00:00
|
|
|
// Regarding *opaque types* specifically, we choose to treat them as non-local,
|
|
|
|
// even those that appear within the same crate. This seems somewhat surprising
|
|
|
|
// at first, but makes sense when 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 anything about it other than the traits that it implements.
|
|
|
|
//
|
|
|
|
// 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 hidden
|
|
|
|
// 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.
|
|
|
|
// Addendum: Moreover, revealing the underlying type is likely to cause cycle
|
|
|
|
// errors as we rely on coherence / the specialization graph during typeck.
|
|
|
|
|
|
|
|
self.found_non_local_ty(ty)
|
2023-10-15 11:40:17 +00:00
|
|
|
}
|
|
|
|
}
|
2022-07-21 09:51:09 +00:00
|
|
|
|
|
|
|
// For fundamental types, we just look inside of them.
|
|
|
|
ty::Ref(_, ty, _) => ty.visit_with(self),
|
2023-07-11 21:35:29 +00:00
|
|
|
ty::Adt(def, args) => {
|
2022-07-21 09:51:09 +00:00
|
|
|
if self.def_id_is_local(def.did()) {
|
|
|
|
ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
|
|
|
|
} else if def.is_fundamental() {
|
2023-07-11 21:35:29 +00:00
|
|
|
args.visit_with(self)
|
2022-07-21 09:51:09 +00:00
|
|
|
} else {
|
|
|
|
self.found_non_local_ty(ty)
|
|
|
|
}
|
2018-12-04 11:28:06 +00:00
|
|
|
}
|
2022-07-21 09:51:09 +00:00
|
|
|
ty::Foreign(def_id) => {
|
|
|
|
if self.def_id_is_local(def_id) {
|
|
|
|
ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
|
|
|
|
} else {
|
|
|
|
self.found_non_local_ty(ty)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
ty::Dynamic(tt, ..) => {
|
|
|
|
let principal = tt.principal().map(|p| p.def_id());
|
2023-05-24 14:19:22 +00:00
|
|
|
if principal.is_some_and(|p| self.def_id_is_local(p)) {
|
2022-07-21 09:51:09 +00:00
|
|
|
ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
|
|
|
|
} else {
|
|
|
|
self.found_non_local_ty(ty)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
ty::Error(_) => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
|
2024-01-24 18:01:56 +00:00
|
|
|
ty::Closure(did, ..) | ty::CoroutineClosure(did, ..) | ty::Coroutine(did, ..) => {
|
2023-01-17 09:39:35 +00:00
|
|
|
if self.def_id_is_local(did) {
|
|
|
|
ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty))
|
|
|
|
} else {
|
|
|
|
self.found_non_local_ty(ty)
|
|
|
|
}
|
2022-07-21 09:51:09 +00:00
|
|
|
}
|
2023-01-17 09:39:35 +00:00
|
|
|
// This should only be created when checking whether we have to check whether some
|
|
|
|
// auto trait impl applies. There will never be multiple impls, so we can just
|
|
|
|
// act as if it were a local type here.
|
2023-10-19 16:06:43 +00:00
|
|
|
ty::CoroutineWitness(..) => ControlFlow::Break(OrphanCheckEarlyExit::LocalTy(ty)),
|
2022-07-21 09:51:09 +00:00
|
|
|
};
|
|
|
|
// A bit of a hack, the `OrphanChecker` is only used to visit a `TraitRef`, so
|
|
|
|
// the first type we visit is always the self type.
|
|
|
|
self.in_self_ty = false;
|
|
|
|
result
|
|
|
|
}
|
2014-09-12 14:54:08 +00:00
|
|
|
|
2022-07-29 07:43:22 +00:00
|
|
|
/// All possible values for a constant parameter already exist
|
|
|
|
/// in the crate defining the trait, so they are always non-local[^1].
|
|
|
|
///
|
|
|
|
/// Because there's no way to have an impl where the first local
|
|
|
|
/// generic argument is a constant, we also don't have to fail
|
|
|
|
/// the orphan check when encountering a parameter or a generic constant.
|
|
|
|
///
|
|
|
|
/// This means that we can completely ignore constants during the orphan check.
|
|
|
|
///
|
2023-01-05 08:45:44 +00:00
|
|
|
/// See `tests/ui/coherence/const-generics-orphan-check-ok.rs` for examples.
|
2022-07-29 07:43:22 +00:00
|
|
|
///
|
|
|
|
/// [^1]: This might not hold for function pointers or trait objects in the future.
|
|
|
|
/// As these should be quite rare as const arguments and especially rare as impl
|
|
|
|
/// parameters, allowing uncovered const parameters in impls seems more useful
|
|
|
|
/// than allowing `impl<T> Trait<local_fn_ptr, T> for i32` to compile.
|
2024-02-24 22:22:28 +00:00
|
|
|
fn visit_const(&mut self, _c: ty::Const<'tcx>) -> Self::Result {
|
2023-01-18 07:17:13 +00:00
|
|
|
ControlFlow::Continue(())
|
2014-09-12 14:54:08 +00:00
|
|
|
}
|
|
|
|
}
|
2023-09-20 19:41:07 +00:00
|
|
|
|
|
|
|
/// Compute the `intercrate_ambiguity_causes` for the new solver using
|
|
|
|
/// "proof trees".
|
|
|
|
///
|
|
|
|
/// This is a bit scuffed but seems to be good enough, at least
|
|
|
|
/// when looking at UI tests. Given that it is only used to improve
|
|
|
|
/// diagnostics this is good enough. We can always improve it once there
|
|
|
|
/// are test cases where it is currently not enough.
|
|
|
|
fn compute_intercrate_ambiguity_causes<'tcx>(
|
|
|
|
infcx: &InferCtxt<'tcx>,
|
|
|
|
obligations: &[PredicateObligation<'tcx>],
|
2023-11-24 18:10:30 +00:00
|
|
|
) -> FxIndexSet<IntercrateAmbiguityCause<'tcx>> {
|
|
|
|
let mut causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>> = Default::default();
|
2023-09-20 19:41:07 +00:00
|
|
|
|
|
|
|
for obligation in obligations {
|
|
|
|
search_ambiguity_causes(infcx, obligation.clone().into(), &mut causes);
|
|
|
|
}
|
|
|
|
|
|
|
|
causes
|
|
|
|
}
|
|
|
|
|
2023-11-24 18:10:30 +00:00
|
|
|
struct AmbiguityCausesVisitor<'a, 'tcx> {
|
|
|
|
causes: &'a mut FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
|
2023-09-20 19:41:07 +00:00
|
|
|
}
|
|
|
|
|
2023-11-24 18:10:30 +00:00
|
|
|
impl<'a, 'tcx> ProofTreeVisitor<'tcx> for AmbiguityCausesVisitor<'a, 'tcx> {
|
2024-03-12 13:26:30 +00:00
|
|
|
fn span(&self) -> Span {
|
|
|
|
DUMMY_SP
|
|
|
|
}
|
|
|
|
|
2024-02-25 00:38:58 +00:00
|
|
|
fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) {
|
2023-09-20 19:41:07 +00:00
|
|
|
let infcx = goal.infcx();
|
|
|
|
for cand in goal.candidates() {
|
2024-03-12 13:26:30 +00:00
|
|
|
cand.visit_nested_in_probe(self);
|
2023-09-20 19:41:07 +00:00
|
|
|
}
|
|
|
|
// When searching for intercrate ambiguity causes, we only need to look
|
|
|
|
// at ambiguous goals, as for others the coherence unknowable candidate
|
|
|
|
// was irrelevant.
|
|
|
|
match goal.result() {
|
|
|
|
Ok(Certainty::Maybe(_)) => {}
|
2024-02-25 00:38:58 +00:00
|
|
|
Ok(Certainty::Yes) | Err(NoSolution) => return,
|
2023-09-20 19:41:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let Goal { param_env, predicate } = goal.goal();
|
|
|
|
|
2024-01-30 01:27:06 +00:00
|
|
|
// For bound predicates we simply call `infcx.enter_forall`
|
2023-09-21 06:56:23 +00:00
|
|
|
// and then prove the resulting predicate as a nested goal.
|
2023-09-20 19:41:07 +00:00
|
|
|
let trait_ref = match predicate.kind().no_bound_vars() {
|
|
|
|
Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(tr))) => tr.trait_ref,
|
2023-11-14 12:55:59 +00:00
|
|
|
Some(ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)))
|
|
|
|
if matches!(
|
2024-05-13 14:00:38 +00:00
|
|
|
infcx.tcx.def_kind(proj.projection_term.def_id),
|
2023-11-14 12:55:59 +00:00
|
|
|
DefKind::AssocTy | DefKind::AssocConst
|
|
|
|
) =>
|
|
|
|
{
|
2024-05-13 14:00:38 +00:00
|
|
|
proj.projection_term.trait_ref(infcx.tcx)
|
2023-09-20 19:41:07 +00:00
|
|
|
}
|
2024-02-25 00:38:58 +00:00
|
|
|
_ => return,
|
2023-09-20 19:41:07 +00:00
|
|
|
};
|
|
|
|
|
2023-11-20 14:01:31 +00:00
|
|
|
// Add ambiguity causes for reservation impls.
|
|
|
|
for cand in goal.candidates() {
|
|
|
|
if let inspect::ProbeKind::TraitCandidate {
|
|
|
|
source: CandidateSource::Impl(def_id),
|
|
|
|
result: Ok(_),
|
|
|
|
} = cand.kind()
|
|
|
|
{
|
|
|
|
if let ty::ImplPolarity::Reservation = infcx.tcx.impl_polarity(def_id) {
|
2023-11-24 18:10:30 +00:00
|
|
|
let message = infcx
|
2023-11-20 14:01:31 +00:00
|
|
|
.tcx
|
|
|
|
.get_attr(def_id, sym::rustc_reservation_impl)
|
|
|
|
.and_then(|a| a.value_str());
|
2023-11-24 18:10:30 +00:00
|
|
|
if let Some(message) = message {
|
|
|
|
self.causes.insert(IntercrateAmbiguityCause::ReservationImpl { message });
|
2023-11-20 14:01:31 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Add ambiguity causes for unknowable goals.
|
2023-09-20 19:41:07 +00:00
|
|
|
let mut ambiguity_cause = None;
|
|
|
|
for cand in goal.candidates() {
|
2024-04-26 17:31:18 +00:00
|
|
|
if let inspect::ProbeKind::TraitCandidate {
|
|
|
|
source: CandidateSource::CoherenceUnknowable,
|
2023-11-23 12:25:41 +00:00
|
|
|
result: Ok(_),
|
|
|
|
} = cand.kind()
|
2023-09-20 19:41:07 +00:00
|
|
|
{
|
2024-05-01 21:22:39 +00:00
|
|
|
let lazily_normalize_ty = |mut ty: Ty<'tcx>| {
|
2023-09-20 19:41:07 +00:00
|
|
|
if matches!(ty.kind(), ty::Alias(..)) {
|
2024-05-01 21:22:39 +00:00
|
|
|
let ocx = ObligationCtxt::new(infcx);
|
|
|
|
ty = ocx
|
|
|
|
.structurally_normalize(&ObligationCause::dummy(), param_env, ty)
|
|
|
|
.map_err(|_| ())?;
|
|
|
|
if !ocx.select_where_possible().is_empty() {
|
|
|
|
return Err(());
|
2023-09-20 19:41:07 +00:00
|
|
|
}
|
|
|
|
}
|
2024-05-01 21:22:39 +00:00
|
|
|
Ok(ty)
|
2023-09-20 19:41:07 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
infcx.probe(|_| {
|
2024-05-02 15:44:05 +00:00
|
|
|
match trait_ref_is_knowable(infcx, trait_ref, lazily_normalize_ty) {
|
2023-09-20 19:41:07 +00:00
|
|
|
Err(()) => {}
|
|
|
|
Ok(Ok(())) => warn!("expected an unknowable trait ref: {trait_ref:?}"),
|
|
|
|
Ok(Err(conflict)) => {
|
|
|
|
if !trait_ref.references_error() {
|
2023-11-27 03:20:45 +00:00
|
|
|
// Normalize the trait ref for diagnostics, ignoring any errors if this fails.
|
|
|
|
let trait_ref =
|
|
|
|
deeply_normalize_for_diagnostics(infcx, param_env, trait_ref);
|
|
|
|
|
2023-09-20 19:41:07 +00:00
|
|
|
let self_ty = trait_ref.self_ty();
|
2023-11-24 18:10:30 +00:00
|
|
|
let self_ty = self_ty.has_concrete_skeleton().then(|| self_ty);
|
2023-09-20 19:41:07 +00:00
|
|
|
ambiguity_cause = Some(match conflict {
|
|
|
|
Conflict::Upstream => {
|
|
|
|
IntercrateAmbiguityCause::UpstreamCrateUpdate {
|
2023-11-24 18:10:30 +00:00
|
|
|
trait_ref,
|
|
|
|
self_ty,
|
2023-09-20 19:41:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Conflict::Downstream => {
|
|
|
|
IntercrateAmbiguityCause::DownstreamCrate {
|
2023-11-24 18:10:30 +00:00
|
|
|
trait_ref,
|
|
|
|
self_ty,
|
2023-09-20 19:41:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2023-09-21 06:56:23 +00:00
|
|
|
} else {
|
|
|
|
match cand.result() {
|
|
|
|
// We only add an ambiguity cause if the goal would otherwise
|
|
|
|
// result in an error.
|
|
|
|
//
|
|
|
|
// FIXME: While this matches the behavior of the
|
|
|
|
// old solver, it is not the only way in which the unknowable
|
|
|
|
// candidates *weaken* coherence, they can also force otherwise
|
|
|
|
// sucessful normalization to be ambiguous.
|
|
|
|
Ok(Certainty::Maybe(_) | Certainty::Yes) => {
|
|
|
|
ambiguity_cause = None;
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
Err(NoSolution) => continue,
|
|
|
|
}
|
2023-09-20 19:41:07 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if let Some(ambiguity_cause) = ambiguity_cause {
|
|
|
|
self.causes.insert(ambiguity_cause);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn search_ambiguity_causes<'tcx>(
|
|
|
|
infcx: &InferCtxt<'tcx>,
|
|
|
|
goal: Goal<'tcx, ty::Predicate<'tcx>>,
|
2023-11-24 18:10:30 +00:00
|
|
|
causes: &mut FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
|
2023-09-20 19:41:07 +00:00
|
|
|
) {
|
2024-03-12 13:26:30 +00:00
|
|
|
infcx.probe(|_| infcx.visit_proof_tree(goal, &mut AmbiguityCausesVisitor { causes }));
|
2023-09-20 19:41:07 +00:00
|
|
|
}
|