use std::fmt::Debug;
use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::{Diag, EmissionGuarantee};
use rustc_hir::def::DefKind;
use rustc_hir::def_id::DefId;
use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
use rustc_middle::bug;
use rustc_middle::traits::query::NoSolution;
use rustc_middle::traits::solve::{CandidateSource, Certainty, Goal};
use rustc_middle::traits::specialization_graph::OverlapMode;
use rustc_middle::ty::fast_reject::{DeepRejectCtxt, TreatParams};
use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor};
use rustc_middle::ty::{self, Ty, TyCtxt};
pub use rustc_next_trait_solver::coherence::*;
use rustc_span::symbol::sym;
use rustc_span::{Span, DUMMY_SP};
use tracing::{debug, instrument, warn};
use super::ObligationCtxt;
use crate::error_reporting::traits::suggest_new_overflow_limit;
use crate::infer::outlives::env::OutlivesEnvironment;
use crate::infer::InferOk;
use crate::solve::inspect::{InspectGoal, ProofTreeInferCtxtExt, ProofTreeVisitor};
use crate::solve::{deeply_normalize_for_diagnostics, inspect};
use crate::traits::select::IntercrateAmbiguityCause;
use crate::traits::{
util, FulfillmentErrorCode, NormalizeExt, Obligation, ObligationCause, PredicateObligation,
SelectionContext, SkipLeakCheck,
};
pub struct OverlapResult<'tcx> {
pub impl_header: ty::ImplHeader<'tcx>,
pub intercrate_ambiguity_causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
pub involves_placeholder: bool,
pub overflowing_predicates: Vec<ty::Predicate<'tcx>>,
}
pub fn add_placeholder_note<G: EmissionGuarantee>(err: &mut Diag<'_, G>) {
err.note(
"this behavior recently changed as a result of a bug fix; \
see rust-lang/rust#56105 for details",
);
}
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);
}
#[derive(Debug, Clone, Copy)]
enum TrackAmbiguityCauses {
Yes,
No,
}
impl TrackAmbiguityCauses {
fn is_yes(self) -> bool {
match self {
TrackAmbiguityCauses::Yes => true,
TrackAmbiguityCauses::No => false,
}
}
}
#[instrument(skip(tcx, skip_leak_check), level = "debug")]
pub fn overlapping_impls(
tcx: TyCtxt<'_>,
impl1_def_id: DefId,
impl2_def_id: DefId,
skip_leak_check: SkipLeakCheck,
overlap_mode: OverlapMode,
) -> Option<OverlapResult<'_>> {
let drcx = DeepRejectCtxt::new(tcx, TreatParams::AsCandidateKey);
let impl1_ref = tcx.impl_trait_ref(impl1_def_id);
let impl2_ref = tcx.impl_trait_ref(impl2_def_id);
let may_overlap = match (impl1_ref, impl2_ref) {
(Some(a), Some(b)) => drcx.args_may_unify(a.skip_binder().args, b.skip_binder().args),
(None, None) => {
let self_ty1 = tcx.type_of(impl1_def_id).skip_binder();
let self_ty2 = tcx.type_of(impl2_def_id).skip_binder();
drcx.types_may_unify(self_ty1, self_ty2)
}
_ => bug!("unexpected impls: {impl1_def_id:?} {impl2_def_id:?}"),
};
if !may_overlap {
debug!("overlapping_impls: fast_reject early-exit");
return None;
}
let _overlap_with_bad_diagnostics = overlap(
tcx,
TrackAmbiguityCauses::No,
skip_leak_check,
impl1_def_id,
impl2_def_id,
overlap_mode,
)?;
let overlap = overlap(
tcx,
TrackAmbiguityCauses::Yes,
skip_leak_check,
impl1_def_id,
impl2_def_id,
overlap_mode,
)
.unwrap();
Some(overlap)
}
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);
ty::ImplHeader {
impl_def_id,
impl_args,
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)),
predicates: tcx
.predicates_of(impl_def_id)
.instantiate(tcx, impl_args)
.iter()
.map(|(c, _)| c.as_predicate())
.collect(),
}
}
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);
let InferOk { value: mut header, obligations } =
infcx.at(&ObligationCause::dummy(), param_env).normalize(header);
header.predicates.extend(obligations.into_iter().map(|o| o.predicate));
header
}
#[instrument(level = "debug", skip(tcx))]
fn overlap<'tcx>(
tcx: TyCtxt<'tcx>,
track_ambiguity_causes: TrackAmbiguityCauses,
skip_leak_check: SkipLeakCheck,
impl1_def_id: DefId,
impl2_def_id: DefId,
overlap_mode: OverlapMode,
) -> Option<OverlapResult<'tcx>> {
if overlap_mode.use_negative_impl() {
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)
{
return None;
}
}
let infcx = tcx
.infer_ctxt()
.skip_leak_check(skip_leak_check.is_yes())
.intercrate(true)
.with_next_trait_solver(tcx.next_trait_solver_in_coherence())
.build();
let selcx = &mut SelectionContext::new(&infcx);
if track_ambiguity_causes.is_yes() {
selcx.enable_tracking_intercrate_ambiguity_causes();
}
let param_env = ty::ParamEnv::empty();
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);
let mut obligations =
equate_impl_headers(selcx.infcx, param_env, &impl1_header, &impl2_header)?;
debug!("overlap: unification check succeeded");
obligations.extend(
[&impl1_header.predicates, &impl2_header.predicates].into_iter().flatten().map(
|&predicate| Obligation::new(infcx.tcx, ObligationCause::dummy(), param_env, predicate),
),
);
let mut overflowing_predicates = Vec::new();
if overlap_mode.use_implicit_negative() {
match impl_intersection_has_impossible_obligation(selcx, &obligations) {
IntersectionHasImpossibleObligations::Yes => return None,
IntersectionHasImpossibleObligations::No { overflowing_predicates: p } => {
overflowing_predicates = p
}
}
}
if infcx.leak_check(ty::UniverseIndex::ROOT, None).is_err() {
debug!("overlap: leak check failed");
return None;
}
let intercrate_ambiguity_causes = if !overlap_mode.use_implicit_negative() {
Default::default()
} else if infcx.next_trait_solver() {
compute_intercrate_ambiguity_causes(&infcx, &obligations)
} else {
selcx.take_intercrate_ambiguity_causes()
};
debug!("overlap: intercrate_ambiguity_causes={:#?}", intercrate_ambiguity_causes);
let involves_placeholder = infcx
.inner
.borrow_mut()
.unwrap_region_constraints()
.data()
.constraints
.iter()
.any(|c| c.0.involves_placeholders());
let mut impl_header = infcx.resolve_vars_if_possible(impl1_header);
if infcx.next_trait_solver() {
impl_header = deeply_normalize_for_diagnostics(&infcx, param_env, impl_header);
}
Some(OverlapResult {
impl_header,
intercrate_ambiguity_causes,
involves_placeholder,
overflowing_predicates,
})
}
#[instrument(level = "debug", skip(infcx), ret)]
fn equate_impl_headers<'tcx>(
infcx: &InferCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
impl1: &ty::ImplHeader<'tcx>,
impl2: &ty::ImplHeader<'tcx>,
) -> Option<Vec<PredicateObligation<'tcx>>> {
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,
),
_ => bug!("equate_impl_headers given mismatched impl kinds"),
};
result.map(|infer_ok| infer_ok.obligations).ok()
}
enum IntersectionHasImpossibleObligations<'tcx> {
Yes,
No {
overflowing_predicates: Vec<ty::Predicate<'tcx>>,
},
}
fn impl_intersection_has_impossible_obligation<'a, 'cx, 'tcx>(
selcx: &mut SelectionContext<'cx, 'tcx>,
obligations: &'a [PredicateObligation<'tcx>],
) -> IntersectionHasImpossibleObligations<'tcx> {
let infcx = selcx.infcx;
if infcx.next_trait_solver() {
let ocx = ObligationCtxt::new_with_diagnostics(infcx);
ocx.register_obligations(obligations.iter().cloned());
let errors_and_ambiguities = ocx.select_all_or_error();
let (errors, ambiguities): (Vec<_>, Vec<_>) =
errors_and_ambiguities.into_iter().partition(|error| error.is_true_error());
if errors.is_empty() {
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(),
}
} else {
IntersectionHasImpossibleObligations::Yes
}
} else {
for obligation in obligations {
let evaluation_result = selcx.evaluate_root_obligation(obligation);
match evaluation_result {
Ok(result) => {
if !result.may_apply() {
return IntersectionHasImpossibleObligations::Yes;
}
}
Err(_overflow) => {}
}
}
IntersectionHasImpossibleObligations::No { overflowing_predicates: Vec::new() }
}
}
fn impl_intersection_has_negative_obligation(
tcx: TyCtxt<'_>,
impl1_def_id: DefId,
impl2_def_id: DefId,
) -> bool {
debug!("negative_impl(impl1_def_id={:?}, impl2_def_id={:?})", impl1_def_id, impl2_def_id);
let ref infcx = tcx.infer_ctxt().intercrate(true).with_next_trait_solver(true).build();
let root_universe = infcx.universe();
assert_eq!(root_universe, ty::UniverseIndex::ROOT);
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);
let Some(equate_obligations) =
equate_impl_headers(infcx, param_env, &impl1_header, &impl2_header)
else {
return false;
};
drop(equate_obligations);
drop(infcx.take_registered_region_obligations());
drop(infcx.take_and_reset_region_constraints());
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);
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))
}
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> {
fn visit_ty(&mut self, ty: Ty<'tcx>) {
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(
DefineOpaqueTypes::Yes,
ty,
Ty::new_placeholder(
self.infcx.tcx,
ty::Placeholder {
universe: self.universe,
bound: ty::BoundTy {
var: self.next_var(),
kind: ty::BoundTyKind::Anon,
},
},
),
)
else {
bug!("we always expect to be able to plug an infer var with placeholder")
};
assert_eq!(obligations, &[]);
} else {
ty.super_visit_with(self);
}
}
fn visit_const(&mut self, ct: ty::Const<'tcx>) {
let ct = self.infcx.shallow_resolve_const(ct);
if ct.is_ct_infer() {
let Ok(InferOk { value: (), obligations }) =
self.infcx.at(&ObligationCause::dummy(), ty::ParamEnv::empty()).eq(
DefineOpaqueTypes::Yes,
ct,
ty::Const::new_placeholder(
self.infcx.tcx,
ty::Placeholder { universe: self.universe, bound: self.next_var() },
),
)
else {
bug!("we always expect to be able to plug an infer var with placeholder")
};
assert_eq!(obligations, &[]);
} else {
ct.super_visit_with(self);
}
}
fn visit_region(&mut self, r: ty::Region<'tcx>) {
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(
DefineOpaqueTypes::Yes,
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 {
bug!("we always expect to be able to plug an infer var with placeholder")
};
assert_eq!(obligations, &[]);
}
}
}
}
value.visit_with(&mut PlugInferWithPlaceholder { infcx, universe, var: ty::BoundVar::ZERO });
}
fn try_prove_negated_where_clause<'tcx>(
root_infcx: &InferCtxt<'tcx>,
clause: ty::Clause<'tcx>,
param_env: ty::ParamEnv<'tcx>,
) -> bool {
let Some(negative_predicate) = clause.as_predicate().flip_polarity(root_infcx.tcx) else {
return false;
};
let ref infcx = root_infcx.fork_with_intercrate(false);
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() {
return false;
}
let outlives_env = OutlivesEnvironment::new(param_env);
let errors = ocx.resolve_regions(&outlives_env);
if !errors.is_empty() {
return false;
}
true
}
fn compute_intercrate_ambiguity_causes<'tcx>(
infcx: &InferCtxt<'tcx>,
obligations: &[PredicateObligation<'tcx>],
) -> FxIndexSet<IntercrateAmbiguityCause<'tcx>> {
let mut causes: FxIndexSet<IntercrateAmbiguityCause<'tcx>> = Default::default();
for obligation in obligations {
search_ambiguity_causes(infcx, obligation.clone().into(), &mut causes);
}
causes
}
struct AmbiguityCausesVisitor<'a, 'tcx> {
causes: &'a mut FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
}
impl<'a, 'tcx> ProofTreeVisitor<'tcx> for AmbiguityCausesVisitor<'a, 'tcx> {
fn span(&self) -> Span {
DUMMY_SP
}
fn visit_goal(&mut self, goal: &InspectGoal<'_, 'tcx>) {
let infcx = goal.infcx();
for cand in goal.candidates() {
cand.visit_nested_in_probe(self);
}
match goal.result() {
Ok(Certainty::Maybe(_)) => {}
Ok(Certainty::Yes) | Err(NoSolution) => return,
}
let Goal { param_env, predicate } = goal.goal();
let trait_ref = match predicate.kind().no_bound_vars() {
Some(ty::PredicateKind::Clause(ty::ClauseKind::Trait(tr))) => tr.trait_ref,
Some(ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)))
if matches!(
infcx.tcx.def_kind(proj.projection_term.def_id),
DefKind::AssocTy | DefKind::AssocConst
) =>
{
proj.projection_term.trait_ref(infcx.tcx)
}
_ => return,
};
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) {
let message = infcx
.tcx
.get_attr(def_id, sym::rustc_reservation_impl)
.and_then(|a| a.value_str());
if let Some(message) = message {
self.causes.insert(IntercrateAmbiguityCause::ReservationImpl { message });
}
}
}
}
let mut ambiguity_cause = None;
for cand in goal.candidates() {
if let inspect::ProbeKind::TraitCandidate {
source: CandidateSource::CoherenceUnknowable,
result: Ok(_),
} = cand.kind()
{
let lazily_normalize_ty = |mut ty: Ty<'tcx>| {
if matches!(ty.kind(), ty::Alias(..)) {
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(());
}
}
Ok(ty)
};
infcx.probe(|_| {
match trait_ref_is_knowable(infcx, trait_ref, lazily_normalize_ty) {
Err(()) => {}
Ok(Ok(())) => warn!("expected an unknowable trait ref: {trait_ref:?}"),
Ok(Err(conflict)) => {
if !trait_ref.references_error() {
let trait_ref =
deeply_normalize_for_diagnostics(infcx, param_env, trait_ref);
let self_ty = trait_ref.self_ty();
let self_ty = self_ty.has_concrete_skeleton().then(|| self_ty);
ambiguity_cause = Some(match conflict {
Conflict::Upstream => {
IntercrateAmbiguityCause::UpstreamCrateUpdate {
trait_ref,
self_ty,
}
}
Conflict::Downstream => {
IntercrateAmbiguityCause::DownstreamCrate {
trait_ref,
self_ty,
}
}
});
}
}
}
})
} else {
match cand.result() {
Ok(Certainty::Maybe(_) | Certainty::Yes) => {
ambiguity_cause = None;
break;
}
Err(NoSolution) => continue,
}
}
}
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>>,
causes: &mut FxIndexSet<IntercrateAmbiguityCause<'tcx>>,
) {
infcx.probe(|_| infcx.visit_proof_tree(goal, &mut AmbiguityCausesVisitor { causes }));
}