1use std::ops::ControlFlow;
2
3use rustc_attr_ir::lang_items::LangItem;
4use rustc_errors::{Applicability, Diag, E0283, E0284, E0790, MultiSpan, struct_span_code_err};
5use rustc_hir as hir;
6use rustc_hir::def::{DefKind, Res};
7use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
8use rustc_hir::intravisit::Visitor as _;
9use rustc_infer::infer::{BoundRegionConversionTime, InferCtxt};
10use rustc_infer::traits::util::elaborate;
11use rustc_infer::traits::{
12 Obligation, ObligationCause, ObligationCauseCode, PolyTraitObligation, PredicateObligation,
13};
14use rustc_middle::ty::consts::ConstExt;
15use rustc_middle::ty::print::PrintPolyTraitClauseExt;
16use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable as _, TypeVisitableExt as _, Unnormalized};
17use rustc_session::diagnostics::feature_err_unstable_feature_bound;
18use rustc_span::{DUMMY_SP, ErrorGuaranteed, Span};
19use tracing::{debug, instrument};
20
21use crate::error_reporting::TypeErrCtxt;
22use crate::error_reporting::infer::need_type_info::TypeAnnotationNeeded;
23use crate::error_reporting::traits::{FindExprBySpan, to_pretty_impl_header};
24use crate::traits::query::evaluate_obligation::InferCtxtExt;
25use crate::traits::{FulfillmentError, ObligationCtxt};
26
27#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CandidateSource {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::DefId(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "DefId",
&__self_0),
Self::ParamEnv(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"ParamEnv", &__self_0),
}
}
}Debug)]
28pub enum CandidateSource {
29 DefId(DefId),
30 ParamEnv(Span),
31}
32
33pub fn compute_applicable_impls_for_diagnostics<'tcx>(
34 infcx: &InferCtxt<'tcx>,
35 obligation: &PolyTraitObligation<'tcx>,
36 ignore_predicates_of_impls: bool,
37) -> Vec<CandidateSource> {
38 let tcx = infcx.tcx;
39 let param_env = obligation.param_env;
40
41 let predicate_polarity = obligation.predicate.skip_binder().polarity;
42
43 let impl_may_apply = |impl_def_id| {
44 let ocx = ObligationCtxt::new(infcx);
45 infcx.enter_forall(obligation.predicate, |placeholder_obligation| {
46 let obligation_trait_ref = ocx.normalize(
47 &ObligationCause::dummy(),
48 param_env,
49 Unnormalized::new_wip(placeholder_obligation.trait_ref),
50 );
51
52 let impl_args = infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
53 let impl_trait_ref =
54 tcx.impl_trait_ref(impl_def_id).instantiate(tcx, impl_args).skip_norm_wip();
55 let impl_trait_ref = ocx.normalize(
56 &ObligationCause::dummy(),
57 param_env,
58 Unnormalized::new_wip(impl_trait_ref),
59 );
60
61 if let Err(_) =
62 ocx.eq(&ObligationCause::dummy(), param_env, obligation_trait_ref, impl_trait_ref)
63 {
64 return false;
65 }
66
67 let impl_trait_header = tcx.impl_trait_header(impl_def_id);
68 let impl_polarity = impl_trait_header.polarity;
69
70 match (impl_polarity, predicate_polarity) {
71 (ty::ImplPolarity::Positive, ty::ClausePolarity::Positive)
72 | (ty::ImplPolarity::Negative, ty::ClausePolarity::Negative) => {}
73 _ => return false,
74 }
75
76 if !ignore_predicates_of_impls {
77 let obligations = tcx
78 .clauses_of(impl_def_id)
79 .instantiate(tcx, impl_args)
80 .into_iter()
81 .map(|(clause, _)| {
82 Obligation::new(
83 tcx,
84 ObligationCause::dummy(),
85 param_env,
86 clause.skip_norm_wip(),
87 )
88 })
89 .filter(|obligation| {
94 infcx.next_trait_solver() || infcx.evaluate_obligation(obligation).is_ok()
95 });
96 ocx.register_obligations(obligations);
97 }
98
99 ocx.try_evaluate_obligations().no_errors()
100 })
101 };
102
103 let param_env_candidate_may_apply = |poly_trait_predicate: ty::PolyTraitClause<'tcx>| {
104 let ocx = ObligationCtxt::new(infcx);
105 infcx.enter_forall(obligation.predicate, |placeholder_obligation| {
106 let obligation_trait_ref = ocx.normalize(
107 &ObligationCause::dummy(),
108 param_env,
109 Unnormalized::new_wip(placeholder_obligation.trait_ref),
110 );
111
112 let param_env_predicate = infcx.instantiate_binder_with_fresh_vars(
113 DUMMY_SP,
114 BoundRegionConversionTime::HigherRankedType,
115 poly_trait_predicate,
116 );
117 let param_env_trait_ref = ocx.normalize(
118 &ObligationCause::dummy(),
119 param_env,
120 Unnormalized::new_wip(param_env_predicate.trait_ref),
121 );
122
123 if let Err(_) = ocx.eq(
124 &ObligationCause::dummy(),
125 param_env,
126 obligation_trait_ref,
127 param_env_trait_ref,
128 ) {
129 return false;
130 }
131
132 ocx.try_evaluate_obligations().no_errors()
133 })
134 };
135
136 let mut ambiguities = Vec::new();
137
138 tcx.for_each_relevant_impl(
139 obligation.predicate.def_id(),
140 obligation.predicate.skip_binder().trait_ref.self_ty(),
141 |impl_def_id| {
142 if infcx.probe(|_| impl_may_apply(impl_def_id)) {
143 ambiguities.push(CandidateSource::DefId(impl_def_id))
144 }
145 },
146 );
147
148 let body_def_id = obligation.cause.body_def_id;
154 if body_def_id != CRATE_DEF_ID {
155 let clauses = tcx.clauses_of(body_def_id.to_def_id()).instantiate_identity(tcx);
156 for (clause, span) in
157 elaborate(tcx, clauses.into_iter().map(|(c, s)| (c.skip_norm_wip(), s)))
158 {
159 let kind = clause.kind();
160 if let ty::ClauseKind::Trait(trait_pred) = kind.skip_binder()
161 && param_env_candidate_may_apply(kind.rebind(trait_pred))
162 {
163 if kind.rebind(trait_pred.trait_ref)
164 == ty::Binder::dummy(ty::TraitRef::identity(tcx, trait_pred.def_id()))
165 {
166 ambiguities.push(CandidateSource::ParamEnv(tcx.def_span(trait_pred.def_id())))
167 } else {
168 ambiguities.push(CandidateSource::ParamEnv(span))
169 }
170 }
171 }
172 }
173
174 ambiguities
175}
176
177impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
178 pub(super) fn ambiguity_term(&self, predicate: ty::Predicate<'tcx>) -> Option<ty::Term<'tcx>> {
185 match predicate.kind().skip_binder() {
186 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
187 data.trait_ref.args.terms().find(|term| term.has_non_region_infer())
188 }
189 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => data
190 .projection_term
191 .args
192 .terms()
193 .chain([data.term])
194 .find(|term| term.has_non_region_infer()),
195 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => Some(term),
196 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(data)) => {
197 data.walk().filter_map(ty::GenericArg::as_term).find(|term| term.is_infer())
198 }
199 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _)) => Some(ct.into()),
200 ty::PredicateKind::Subtype(data) => Some(data.a.into()),
201 ty::PredicateKind::NormalizesTo(data) if data.term.is_infer() => Some(data.term),
202 _ => None,
203 }
204 }
205
206 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("maybe_report_ambiguity",
"rustc_trait_selection::error_reporting::traits::ambiguity",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs"),
::tracing_core::__macro_support::Option::Some(206u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::ambiguity"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("obligation")
}> =
::tracing::__macro_support::FieldName::new("obligation");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("related")
}> =
::tracing::__macro_support::FieldName::new("related");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&related)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ErrorGuaranteed = loop {};
return __tracing_attr_fake_return;
}
{
let predicate =
self.deeply_resolve_ignoring_regions(obligation.predicate);
let span = obligation.cause.span;
let mut long_ty_path = None;
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs:221",
"rustc_trait_selection::error_reporting::traits::ambiguity",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs"),
::tracing_core::__macro_support::Option::Some(221u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::ambiguity"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("predicate")
}> =
::tracing::__macro_support::FieldName::new("predicate");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("obligation.cause.code")
}> =
::tracing::__macro_support::FieldName::new("obligation.cause.code");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&predicate)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&obligation.cause.code())
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
let bound_predicate = predicate.kind();
let mut err =
match bound_predicate.skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
let trait_pred = bound_predicate.rebind(data);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs:230",
"rustc_trait_selection::error_reporting::traits::ambiguity",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/d080e7dff1b0fc54541545252818f8cccf995d05/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs"),
::tracing_core::__macro_support::Option::Some(230u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::ambiguity"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("trait_pred")
}> =
::tracing::__macro_support::FieldName::new("trait_pred");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&trait_pred)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
if let Err(e) = predicate.error_reported() { return e; }
if let Err(guar) =
self.tcx.ensure_result().coherent_trait(trait_pred.def_id())
{
return guar;
}
if #[allow(non_exhaustive_omitted_patterns)] match self.tcx.as_lang_item(trait_pred.def_id())
{
Some(LangItem::Sized | LangItem::MetaSized) => true,
_ => false,
} {
return match self.tainted_by_errors() {
None =>
self.emit_inference_failure_err(obligation.cause.body_def_id,
span, trait_pred.self_ty().skip_binder().into(),
TypeAnnotationNeeded::E0282, false).emit_err(),
Some(e) => e,
};
}
let term = self.ambiguity_term(predicate);
let mut err =
if let Some(term) = term {
let candidates: Vec<_> =
self.tcx.all_impls(trait_pred.def_id()).filter_map(|def_id|
{
let imp = self.tcx.impl_trait_header(def_id);
if imp.polarity != ty::ImplPolarity::Positive ||
!self.tcx.is_user_visible_dep(def_id.krate) {
return None;
}
let imp = imp.trait_ref.skip_binder();
if imp.with_replaced_self_ty(self.tcx,
trait_pred.skip_binder().self_ty()) ==
trait_pred.skip_binder().trait_ref {
Some(imp.self_ty())
} else { None }
}).collect();
self.emit_inference_failure_err_with_type_hint(obligation.cause.body_def_id,
span, term, TypeAnnotationNeeded::E0283, true,
match &candidates[..] {
[candidate] => Some(*candidate),
_ => None,
})
} else {
{
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type annotations needed: cannot satisfy `{0}`",
self.tcx.short_string(predicate, &mut long_ty_path)))
})).with_code(E0283)
}.with_long_ty_path(long_ty_path)
};
if let Some(ambiguities) =
self.applicable_impls_to_mention(obligation, trait_pred) {
if let Some(e) = self.tainted_by_errors() && term.is_none()
{
err.cancel();
return e;
}
self.annotate_source_of_ambiguity(&mut err, &ambiguities,
predicate);
} else {
if let Some(e) = self.tainted_by_errors() {
err.cancel();
return e;
}
if let Some(clause) = predicate.as_trait_clause() &&
let ty::Infer(_) = clause.self_ty().skip_binder().kind() {
let tr =
self.tcx.short_string(clause.print_modifiers_and_trait_path(),
&mut err.long_ty_path());
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the type must implement `{0}`",
tr))
}));
} else {
let pred =
self.tcx.short_string(predicate, &mut err.long_ty_path());
err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot satisfy `{0}`",
pred))
}));
}
let impl_candidates =
self.find_similar_impl_candidates(predicate.as_trait_clause().unwrap());
if impl_candidates.len() < 40 {
self.report_similar_impl_candidates(impl_candidates.as_slice(),
obligation, trait_pred, obligation.cause.body_def_id,
&mut err, false, obligation.param_env);
}
}
if let ObligationCauseCode::WhereClause(def_id, _) |
ObligationCauseCode::WhereClauseInExpr(def_id, ..) =
*obligation.cause.code() {
self.suggest_fully_qualified_path(&mut err, def_id, span,
trait_pred.def_id());
}
if term.is_some_and(|term| term.as_type().is_some()) &&
let Some(body) =
self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id)
{
let mut expr_finder = FindExprBySpan::new(span, self.tcx);
expr_finder.visit_expr(&body.value);
if let Some(hir::Expr {
kind: hir::ExprKind::Call(hir::Expr {
kind: hir::ExprKind::Path(hir::QPath::Resolved(None, path)),
.. }, _) |
hir::ExprKind::Path(hir::QPath::Resolved(None, path)), .. })
= expr_finder.result &&
let [.., trait_path_segment @ hir::PathSegment {
res: Res::Def(DefKind::Trait, trait_id), .. },
hir::PathSegment {
ident: assoc_item_ident, res: Res::Def(_, item_id), .. }] =
path.segments && data.trait_ref.def_id == *trait_id &&
self.tcx.trait_of_assoc(*item_id) == Some(*trait_id) &&
let None = self.tainted_by_errors() {
let assoc_item = self.tcx.associated_item(*item_id);
let (verb, noun) =
match assoc_item.kind {
ty::AssocKind::Const { .. } => ("refer to the", "constant"),
ty::AssocKind::Fn { .. } => ("call", "function"),
ty::AssocKind::Type { .. } => ("refer to the", "type"),
};
err.cancel();
err =
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot {0} associated {1} on trait without specifying the corresponding `impl` type",
verb, noun))
}));
err.code(E0790);
if item_id.is_local() {
let trait_ident = self.tcx.item_name(*trait_id);
err.span_label(self.tcx.def_span(*item_id),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}::{1}` defined here",
trait_ident, assoc_item_ident))
}));
}
err.span_label(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot {0} associated {1} of trait",
verb, noun))
}));
let trait_impls =
self.tcx.trait_impls_of(data.trait_ref.def_id);
if let Some(&impl_def_id) =
trait_impls.non_blanket_impls().values().flatten().next() {
let non_blanket_impl_count =
trait_impls.non_blanket_impls().values().flatten().count();
let (message, self_types) =
if non_blanket_impl_count == 1 {
("use the fully-qualified path to the only available \
implementation",
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}",
self.tcx.type_of(impl_def_id).instantiate_identity().skip_norm_wip()))
})])))
} else if non_blanket_impl_count < 20 {
("use a fully-qualified path to one of the available \
implementations",
trait_impls.non_blanket_impls().values().flatten().map(|&id|
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}",
self.tcx.type_of(id).instantiate_identity().skip_norm_wip()))
})
}).collect::<Vec<String>>())
} else {
("use a fully-qualified path to a specific available \
implementation",
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
["/* self type */".to_string()])))
};
let suggestions: Vec<_> =
self_types.into_iter().map(|self_type|
{
let mut suggestions =
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(path.span.shrink_to_lo(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0} as ", self_type))
}))]));
if let Some(generic_arg) = trait_path_segment.args {
let between_span =
trait_path_segment.ident.span.between(generic_arg.span_ext);
suggestions.push((between_span, "".to_string()));
suggestions.push((generic_arg.span_ext.shrink_to_hi(),
">".to_string()));
} else {
suggestions.push((trait_path_segment.ident.span.shrink_to_hi(),
">".to_string()));
}
suggestions
}).collect();
err.multipart_suggestions(message, suggestions,
Applicability::MaybeIncorrect);
}
}
};
err
}
ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term))
=> {
if let Err(e) = term.error_reported() { return e; }
if let Some(e) = self.tainted_by_errors() { return e; }
self.emit_inference_failure_err(obligation.cause.body_def_id,
span, term, TypeAnnotationNeeded::E0282, false)
}
ty::PredicateKind::Subtype(data) => {
if let Err(e) = data.error_reported() { return e; }
if let Some(e) = self.tainted_by_errors() { return e; }
let ty::SubtypePredicate { a_is_expected: _, a, b } = data;
if !(a.is_ty_var() && b.is_ty_var()) {
::core::panicking::panic("assertion failed: a.is_ty_var() && b.is_ty_var()")
};
self.emit_inference_failure_err(obligation.cause.body_def_id,
span, a.into(), TypeAnnotationNeeded::E0282, true)
}
ty::PredicateKind::Clause(ty::ClauseKind::Projection(data))
=> {
if let Err(e) = predicate.error_reported() { return e; }
if let Some(e) = self.tainted_by_errors() { return e; }
if data.projection_term.kind.is_trait_projection() &&
let Err(guar) =
self.tcx.ensure_result().coherent_trait(self.tcx.parent(data.def_id()))
{
return guar;
}
let term = self.ambiguity_term(predicate);
let predicate =
self.tcx.short_string(predicate, &mut long_ty_path);
if let Some(term) = term {
self.emit_inference_failure_err(obligation.cause.body_def_id,
span, term, TypeAnnotationNeeded::E0284,
true).with_note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot satisfy `{0}`",
predicate))
})).with_long_ty_path(long_ty_path)
} else {
{
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type annotations needed: cannot satisfy `{0}`",
predicate))
})).with_code(E0284)
}.with_span_label(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot satisfy `{0}`",
predicate))
})).with_long_ty_path(long_ty_path)
}
}
ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(_))
=> {
if let Err(e) = predicate.error_reported() { return e; }
if let Some(e) = self.tainted_by_errors() { return e; }
if let Some(term) = self.ambiguity_term(predicate) {
self.emit_inference_failure_err(obligation.cause.body_def_id,
span, term, TypeAnnotationNeeded::E0284, true)
} else {
let predicate =
self.tcx.short_string(predicate, &mut long_ty_path);
{
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type annotations needed: cannot satisfy `{0}`",
predicate))
})).with_code(E0284)
}.with_span_label(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot satisfy `{0}`",
predicate))
})).with_long_ty_path(long_ty_path)
}
}
ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct,
..)) =>
self.emit_inference_failure_err(obligation.cause.body_def_id,
span, ct.into(), TypeAnnotationNeeded::E0284, true),
ty::PredicateKind::NormalizesTo(ty::NormalizesTo {
alias, term }) if term.is_infer() => {
if let Some(e) = self.tainted_by_errors() { return e; }
let alias = self.tcx.short_string(alias, &mut long_ty_path);
{
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type annotations needed: cannot normalize `{0}`",
alias))
})).with_code(E0284)
}.with_span_label(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot normalize `{0}`",
alias))
})).with_long_ty_path(long_ty_path)
}
ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(sym))
=> {
if let Some(e) = self.tainted_by_errors() { return e; }
if self.tcx.features().staged_api() {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unstable feature `{0}` is used without being enabled.",
sym))
})).with_help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("The feature can be enabled by marking the current item with `#[unstable_feature_bound({0})]`",
sym))
}))
} else {
feature_err_unstable_feature_bound(&self.tcx.sess, sym,
span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("use of unstable library feature `{0}`",
sym))
}))
}
}
_ => {
if let Some(e) = self.tainted_by_errors() { return e; }
let predicate =
self.tcx.short_string(predicate, &mut long_ty_path);
{
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type annotations needed: cannot satisfy `{0}`",
predicate))
})).with_code(E0284)
}.with_span_label(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot satisfy `{0}`",
predicate))
})).with_long_ty_path(long_ty_path)
}
};
let mut mentioned =
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[predicate]));
let mut mentioned_strs: Vec<String> = ::alloc::vec::Vec::new();
for &error in related {
let related_pred =
self.deeply_resolve_ignoring_regions(error.obligation.predicate);
if mentioned.contains(&related_pred) { continue; }
let note =
match related_pred.kind().skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) if
!#[allow(non_exhaustive_omitted_patterns)] match self.tcx.as_lang_item(data.def_id())
{
Some(LangItem::Sized | LangItem::MetaSized |
LangItem::PointeeSized) => true,
_ => false,
} => {
let clause = related_pred.kind().rebind(data);
if let ty::Infer(_) = clause.self_ty().skip_binder().kind()
{
let tr =
self.tcx.short_string(clause.print_modifiers_and_trait_path(),
&mut err.long_ty_path());
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the type must also implement `{0}`",
tr))
})
} else {
let pred =
self.tcx.short_string(related_pred,
&mut err.long_ty_path());
let note =
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot satisfy `{0}`",
pred))
});
if !mentioned_strs.contains(¬e) &&
self.tainted_by_errors().is_none() &&
let Some(ambiguities) =
self.applicable_impls_to_mention(&error.obligation, clause)
{
self.annotate_source_of_ambiguity(&mut err, &ambiguities,
related_pred);
mentioned_strs.push(note);
mentioned.push(related_pred);
continue;
}
note
}
}
ty::PredicateKind::Clause(ty::ClauseKind::Projection(_)) =>
{
let pred =
self.tcx.short_string(related_pred,
&mut err.long_ty_path());
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot satisfy `{0}`",
pred))
})
}
_ => { mentioned.push(related_pred); continue; }
};
if !mentioned_strs.contains(¬e) {
err.note(note.clone());
mentioned_strs.push(note);
}
mentioned.push(related_pred);
}
self.note_obligation_cause(&mut err, obligation);
for &error in related {
if error.obligation.cause.code() != obligation.cause.code() {
self.note_obligation_cause(&mut err, &error.obligation);
}
}
err.emit_err()
}
}
}#[instrument(skip(self), level = "debug")]
207 pub(super) fn maybe_report_ambiguity(
208 &self,
209 obligation: &PredicateObligation<'tcx>,
210 related: &[&FulfillmentError<'tcx>],
211 ) -> ErrorGuaranteed {
212 let predicate = self.deeply_resolve_ignoring_regions(obligation.predicate);
218 let span = obligation.cause.span;
219 let mut long_ty_path = None;
220
221 debug!(?predicate, obligation.cause.code = ?obligation.cause.code());
222
223 let bound_predicate = predicate.kind();
227 let mut err = match bound_predicate.skip_binder() {
228 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
229 let trait_pred = bound_predicate.rebind(data);
230 debug!(?trait_pred);
231
232 if let Err(e) = predicate.error_reported() {
233 return e;
234 }
235
236 if let Err(guar) = self.tcx.ensure_result().coherent_trait(trait_pred.def_id()) {
237 return guar;
240 }
241
242 if matches!(
258 self.tcx.as_lang_item(trait_pred.def_id()),
259 Some(LangItem::Sized | LangItem::MetaSized)
260 ) {
261 return match self.tainted_by_errors() {
262 None => self
263 .emit_inference_failure_err(
264 obligation.cause.body_def_id,
265 span,
266 trait_pred.self_ty().skip_binder().into(),
267 TypeAnnotationNeeded::E0282,
268 false,
269 )
270 .emit_err(),
271 Some(e) => e,
272 };
273 }
274
275 let term = self.ambiguity_term(predicate);
289
290 let mut err = if let Some(term) = term {
291 let candidates: Vec<_> = self
292 .tcx
293 .all_impls(trait_pred.def_id())
294 .filter_map(|def_id| {
295 let imp = self.tcx.impl_trait_header(def_id);
296 if imp.polarity != ty::ImplPolarity::Positive
297 || !self.tcx.is_user_visible_dep(def_id.krate)
298 {
299 return None;
300 }
301 let imp = imp.trait_ref.skip_binder();
302 if imp
303 .with_replaced_self_ty(self.tcx, trait_pred.skip_binder().self_ty())
304 == trait_pred.skip_binder().trait_ref
305 {
306 Some(imp.self_ty())
307 } else {
308 None
309 }
310 })
311 .collect();
312 self.emit_inference_failure_err_with_type_hint(
313 obligation.cause.body_def_id,
314 span,
315 term,
316 TypeAnnotationNeeded::E0283,
317 true,
318 match &candidates[..] {
319 [candidate] => Some(*candidate),
320 _ => None,
321 },
322 )
323 } else {
324 struct_span_code_err!(
325 self.dcx(),
326 span,
327 E0283,
328 "type annotations needed: cannot satisfy `{}`",
329 self.tcx.short_string(predicate, &mut long_ty_path),
330 )
331 .with_long_ty_path(long_ty_path)
332 };
333
334 if let Some(ambiguities) = self.applicable_impls_to_mention(obligation, trait_pred)
335 {
336 if let Some(e) = self.tainted_by_errors()
337 && term.is_none()
338 {
339 err.cancel();
344 return e;
345 }
346 self.annotate_source_of_ambiguity(&mut err, &ambiguities, predicate);
347 } else {
348 if let Some(e) = self.tainted_by_errors() {
349 err.cancel();
350 return e;
351 }
352 if let Some(clause) = predicate.as_trait_clause()
353 && let ty::Infer(_) = clause.self_ty().skip_binder().kind()
354 {
355 let tr = self.tcx.short_string(
356 clause.print_modifiers_and_trait_path(),
357 &mut err.long_ty_path(),
358 );
359 err.note(format!("the type must implement `{tr}`"));
360 } else {
361 let pred = self.tcx.short_string(predicate, &mut err.long_ty_path());
362 err.note(format!("cannot satisfy `{pred}`"));
363 }
364 let impl_candidates =
365 self.find_similar_impl_candidates(predicate.as_trait_clause().unwrap());
366 if impl_candidates.len() < 40 {
367 self.report_similar_impl_candidates(
368 impl_candidates.as_slice(),
369 obligation,
370 trait_pred,
371 obligation.cause.body_def_id,
372 &mut err,
373 false,
374 obligation.param_env,
375 );
376 }
377 }
378
379 if let ObligationCauseCode::WhereClause(def_id, _)
380 | ObligationCauseCode::WhereClauseInExpr(def_id, ..) = *obligation.cause.code()
381 {
382 self.suggest_fully_qualified_path(&mut err, def_id, span, trait_pred.def_id());
383 }
384
385 if term.is_some_and(|term| term.as_type().is_some())
386 && let Some(body) =
387 self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id)
388 {
389 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
390 expr_finder.visit_expr(&body.value);
391
392 if let Some(hir::Expr {
393 kind:
394 hir::ExprKind::Call(
395 hir::Expr {
396 kind: hir::ExprKind::Path(hir::QPath::Resolved(None, path)),
397 ..
398 },
399 _,
400 )
401 | hir::ExprKind::Path(hir::QPath::Resolved(None, path)),
402 ..
403 }) = expr_finder.result
404 && let [
405 ..,
406 trait_path_segment @ hir::PathSegment {
407 res: Res::Def(DefKind::Trait, trait_id),
408 ..
409 },
410 hir::PathSegment {
411 ident: assoc_item_ident,
412 res: Res::Def(_, item_id),
413 ..
414 },
415 ] = path.segments
416 && data.trait_ref.def_id == *trait_id
417 && self.tcx.trait_of_assoc(*item_id) == Some(*trait_id)
418 && let None = self.tainted_by_errors()
419 {
420 let assoc_item = self.tcx.associated_item(*item_id);
421 let (verb, noun) = match assoc_item.kind {
422 ty::AssocKind::Const { .. } => ("refer to the", "constant"),
423 ty::AssocKind::Fn { .. } => ("call", "function"),
424 ty::AssocKind::Type { .. } => ("refer to the", "type"),
427 };
428
429 err.cancel();
431 err = self.dcx().struct_span_err(
432 span,
433 format!(
434 "cannot {verb} associated {noun} on trait without specifying the \
435 corresponding `impl` type",
436 ),
437 );
438 err.code(E0790);
439
440 if item_id.is_local() {
441 let trait_ident = self.tcx.item_name(*trait_id);
442 err.span_label(
443 self.tcx.def_span(*item_id),
444 format!("`{trait_ident}::{assoc_item_ident}` defined here"),
445 );
446 }
447
448 err.span_label(span, format!("cannot {verb} associated {noun} of trait"));
449
450 let trait_impls = self.tcx.trait_impls_of(data.trait_ref.def_id);
451
452 if let Some(&impl_def_id) =
453 trait_impls.non_blanket_impls().values().flatten().next()
454 {
455 let non_blanket_impl_count =
456 trait_impls.non_blanket_impls().values().flatten().count();
457 let (message, self_types) = if non_blanket_impl_count == 1 {
460 (
461 "use the fully-qualified path to the only available \
462 implementation",
463 vec![format!(
464 "{}",
465 self.tcx
466 .type_of(impl_def_id)
467 .instantiate_identity()
468 .skip_norm_wip()
469 )],
470 )
471 } else if non_blanket_impl_count < 20 {
472 (
473 "use a fully-qualified path to one of the available \
474 implementations",
475 trait_impls
476 .non_blanket_impls()
477 .values()
478 .flatten()
479 .map(|&id| {
480 format!(
481 "{}",
482 self.tcx
483 .type_of(id)
484 .instantiate_identity()
485 .skip_norm_wip()
486 )
487 })
488 .collect::<Vec<String>>(),
489 )
490 } else {
491 (
492 "use a fully-qualified path to a specific available \
493 implementation",
494 vec!["/* self type */".to_string()],
495 )
496 };
497 let suggestions: Vec<_> = self_types
498 .into_iter()
499 .map(|self_type| {
500 let mut suggestions = vec![(
501 path.span.shrink_to_lo(),
502 format!("<{self_type} as "),
503 )];
504 if let Some(generic_arg) = trait_path_segment.args {
505 let between_span = trait_path_segment
506 .ident
507 .span
508 .between(generic_arg.span_ext);
509 suggestions.push((between_span, "".to_string()));
512 suggestions.push((
513 generic_arg.span_ext.shrink_to_hi(),
514 ">".to_string(),
515 ));
516 } else {
517 suggestions.push((
518 trait_path_segment.ident.span.shrink_to_hi(),
519 ">".to_string(),
520 ));
521 }
522 suggestions
523 })
524 .collect();
525 err.multipart_suggestions(
526 message,
527 suggestions,
528 Applicability::MaybeIncorrect,
529 );
530 }
531 }
532 };
533
534 err
535 }
536
537 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
538 if let Err(e) = term.error_reported() {
542 return e;
543 }
544 if let Some(e) = self.tainted_by_errors() {
545 return e;
546 }
547
548 self.emit_inference_failure_err(
549 obligation.cause.body_def_id,
550 span,
551 term,
552 TypeAnnotationNeeded::E0282,
553 false,
554 )
555 }
556
557 ty::PredicateKind::Subtype(data) => {
558 if let Err(e) = data.error_reported() {
559 return e;
560 }
561 if let Some(e) = self.tainted_by_errors() {
562 return e;
563 }
564 let ty::SubtypePredicate { a_is_expected: _, a, b } = data;
565 assert!(a.is_ty_var() && b.is_ty_var());
567 self.emit_inference_failure_err(
568 obligation.cause.body_def_id,
569 span,
570 a.into(),
571 TypeAnnotationNeeded::E0282,
572 true,
573 )
574 }
575
576 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
577 if let Err(e) = predicate.error_reported() {
578 return e;
579 }
580 if let Some(e) = self.tainted_by_errors() {
581 return e;
582 }
583
584 if data.projection_term.kind.is_trait_projection()
585 && let Err(guar) =
586 self.tcx.ensure_result().coherent_trait(self.tcx.parent(data.def_id()))
587 {
588 return guar;
591 }
592 let term = self.ambiguity_term(predicate);
593 let predicate = self.tcx.short_string(predicate, &mut long_ty_path);
594 if let Some(term) = term {
595 self.emit_inference_failure_err(
596 obligation.cause.body_def_id,
597 span,
598 term,
599 TypeAnnotationNeeded::E0284,
600 true,
601 )
602 .with_note(format!("cannot satisfy `{predicate}`"))
603 .with_long_ty_path(long_ty_path)
604 } else {
605 struct_span_code_err!(
607 self.dcx(),
608 span,
609 E0284,
610 "type annotations needed: cannot satisfy `{predicate}`",
611 )
612 .with_span_label(span, format!("cannot satisfy `{predicate}`"))
613 .with_long_ty_path(long_ty_path)
614 }
615 }
616
617 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(_)) => {
618 if let Err(e) = predicate.error_reported() {
619 return e;
620 }
621 if let Some(e) = self.tainted_by_errors() {
622 return e;
623 }
624 if let Some(term) = self.ambiguity_term(predicate) {
625 self.emit_inference_failure_err(
626 obligation.cause.body_def_id,
627 span,
628 term,
629 TypeAnnotationNeeded::E0284,
630 true,
631 )
632 } else {
633 let predicate = self.tcx.short_string(predicate, &mut long_ty_path);
635 struct_span_code_err!(
636 self.dcx(),
637 span,
638 E0284,
639 "type annotations needed: cannot satisfy `{predicate}`",
640 )
641 .with_span_label(span, format!("cannot satisfy `{predicate}`"))
642 .with_long_ty_path(long_ty_path)
643 }
644 }
645
646 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ..)) => self
647 .emit_inference_failure_err(
648 obligation.cause.body_def_id,
649 span,
650 ct.into(),
651 TypeAnnotationNeeded::E0284,
652 true,
653 ),
654
655 ty::PredicateKind::NormalizesTo(ty::NormalizesTo { alias, term })
656 if term.is_infer() =>
657 {
658 if let Some(e) = self.tainted_by_errors() {
659 return e;
660 }
661 let alias = self.tcx.short_string(alias, &mut long_ty_path);
662 struct_span_code_err!(
663 self.dcx(),
664 span,
665 E0284,
666 "type annotations needed: cannot normalize `{alias}`",
667 )
668 .with_span_label(span, format!("cannot normalize `{alias}`"))
669 .with_long_ty_path(long_ty_path)
670 }
671
672 ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(sym)) => {
673 if let Some(e) = self.tainted_by_errors() {
674 return e;
675 }
676
677 if self.tcx.features().staged_api() {
678 self.dcx().struct_span_err(
679 span,
680 format!("unstable feature `{sym}` is used without being enabled."),
681 ).with_help(format!("The feature can be enabled by marking the current item with `#[unstable_feature_bound({sym})]`"))
682 } else {
683 feature_err_unstable_feature_bound(
684 &self.tcx.sess,
685 sym,
686 span,
687 format!("use of unstable library feature `{sym}`"),
688 )
689 }
690 }
691
692 _ => {
693 if let Some(e) = self.tainted_by_errors() {
694 return e;
695 }
696 let predicate = self.tcx.short_string(predicate, &mut long_ty_path);
697 struct_span_code_err!(
698 self.dcx(),
699 span,
700 E0284,
701 "type annotations needed: cannot satisfy `{predicate}`",
702 )
703 .with_span_label(span, format!("cannot satisfy `{predicate}`"))
704 .with_long_ty_path(long_ty_path)
705 }
706 };
707
708 let mut mentioned = vec![predicate];
713 let mut mentioned_strs: Vec<String> = vec![];
714 for &error in related {
715 let related_pred = self.deeply_resolve_ignoring_regions(error.obligation.predicate);
716 if mentioned.contains(&related_pred) {
717 continue;
718 }
719 let note = match related_pred.kind().skip_binder() {
720 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data))
721 if !matches!(
722 self.tcx.as_lang_item(data.def_id()),
723 Some(LangItem::Sized | LangItem::MetaSized | LangItem::PointeeSized)
724 ) =>
725 {
726 let clause = related_pred.kind().rebind(data);
727 if let ty::Infer(_) = clause.self_ty().skip_binder().kind() {
728 let tr = self.tcx.short_string(
729 clause.print_modifiers_and_trait_path(),
730 &mut err.long_ty_path(),
731 );
732 format!("the type must also implement `{tr}`")
733 } else {
734 let pred = self.tcx.short_string(related_pred, &mut err.long_ty_path());
735 let note = format!("cannot satisfy `{pred}`");
736 if !mentioned_strs.contains(¬e)
744 && self.tainted_by_errors().is_none()
745 && let Some(ambiguities) =
746 self.applicable_impls_to_mention(&error.obligation, clause)
747 {
748 self.annotate_source_of_ambiguity(&mut err, &ambiguities, related_pred);
749 mentioned_strs.push(note);
750 mentioned.push(related_pred);
751 continue;
752 }
753 note
754 }
755 }
756 ty::PredicateKind::Clause(ty::ClauseKind::Projection(_)) => {
757 let pred = self.tcx.short_string(related_pred, &mut err.long_ty_path());
758 format!("cannot satisfy `{pred}`")
759 }
760 _ => {
761 mentioned.push(related_pred);
762 continue;
763 }
764 };
765 if !mentioned_strs.contains(¬e) {
768 err.note(note.clone());
769 mentioned_strs.push(note);
770 }
771 mentioned.push(related_pred);
772 }
773
774 self.note_obligation_cause(&mut err, obligation);
775 for &error in related {
779 if error.obligation.cause.code() != obligation.cause.code() {
780 self.note_obligation_cause(&mut err, &error.obligation);
781 }
782 }
783 err.emit_err()
784 }
785
786 fn applicable_impls_to_mention(
789 &self,
790 obligation: &PredicateObligation<'tcx>,
791 trait_pred: ty::PolyTraitClause<'tcx>,
792 ) -> Option<Vec<CandidateSource>> {
793 let mut ambiguities = compute_applicable_impls_for_diagnostics(
794 self.infcx,
795 &obligation.with(self.tcx, trait_pred),
796 false,
797 );
798 let has_non_region_infer =
799 trait_pred.skip_binder().trait_ref.args.types().any(|t| !t.is_ty_or_numeric_infer());
800 if ambiguities.len() > 5 {
804 let infcx = self.infcx;
805 if !ambiguities.iter().all(|option| match option {
806 CandidateSource::DefId(did) => infcx.tcx.generics_of(*did).count() == 0,
807 CandidateSource::ParamEnv(_) => true,
808 }) {
809 ambiguities.retain(|option| match option {
811 CandidateSource::DefId(did) => infcx.tcx.generics_of(*did).count() == 0,
812 CandidateSource::ParamEnv(_) => true,
813 });
814 }
815 }
816 (ambiguities.len() > 1 && ambiguities.len() < 10 && has_non_region_infer)
817 .then_some(ambiguities)
818 }
819
820 fn annotate_source_of_ambiguity(
821 &self,
822 err: &mut Diag<'_>,
823 ambiguities: &[CandidateSource],
824 predicate: ty::Predicate<'tcx>,
825 ) {
826 let mut spans = ::alloc::vec::Vec::new()vec![];
827 let mut crates = ::alloc::vec::Vec::new()vec![];
828 let mut post = ::alloc::vec::Vec::new()vec![];
829 let mut has_param_env = false;
830 for ambiguity in ambiguities {
831 match ambiguity {
832 CandidateSource::DefId(impl_def_id) => match self.tcx.span_of_impl(*impl_def_id) {
833 Ok(span) => spans.push(span),
834 Err(name) => {
835 crates.push(name);
836 if let Some(header) = to_pretty_impl_header(self.tcx, *impl_def_id) {
837 post.push(header);
838 }
839 }
840 },
841 CandidateSource::ParamEnv(span) => {
842 has_param_env = true;
843 spans.push(*span);
844 }
845 }
846 }
847 let mut crate_names: Vec<_> = crates.iter().map(|n| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`")).collect();
848 crate_names.sort();
849 crate_names.dedup();
850 post.sort();
851 post.dedup();
852
853 if self.tainted_by_errors().is_some()
854 && (crate_names.len() == 1
855 && spans.len() == 0
856 && ["`core`", "`alloc`", "`std`"].contains(&crate_names[0].as_str())
857 || predicate.visit_with(&mut HasNumericInferVisitor).is_break())
858 {
859 err.downgrade_to_delayed_bug();
865 return;
866 }
867
868 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("multiple `impl`s{0} satisfying `{1}` found",
if has_param_env { " or `where` clauses" } else { "" },
predicate))
})format!(
869 "multiple `impl`s{} satisfying `{}` found",
870 if has_param_env { " or `where` clauses" } else { "" },
871 predicate
872 );
873 let post = if post.len() > 1 || (post.len() == 1 && post[0].contains('\n')) {
874 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(":\n{0}",
post.iter().map(|p|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("- {0}", p))
})).collect::<Vec<_>>().join("\n")))
})format!(":\n{}", post.iter().map(|p| format!("- {p}")).collect::<Vec<_>>().join("\n"))
875 } else if post.len() == 1 {
876 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": `{0}`", post[0]))
})format!(": `{}`", post[0])
877 } else {
878 String::new()
879 };
880
881 match (spans.len(), crates.len(), crate_names.len()) {
882 (0, 0, 0) => {
883 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot satisfy `{0}`", predicate))
})format!("cannot satisfy `{predicate}`"));
884 }
885 (0, _, 1) => {
886 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1} in the `{0}` crate{2}",
crates[0], msg, post))
})format!("{msg} in the `{}` crate{post}", crates[0]));
887 }
888 (0, _, _) => {
889 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} in the following crates: {1}{2}",
msg, crate_names.join(", "), post))
})format!(
890 "{} in the following crates: {}{}",
891 msg,
892 crate_names.join(", "),
893 post,
894 ));
895 }
896 (_, 0, 0) => {
897 let span: MultiSpan = spans.into();
898 err.span_note(span, msg);
899 }
900 (_, 1, 1) => {
901 let span: MultiSpan = spans.into();
902 err.span_note(span, msg);
903 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("and another `impl` found in the `{0}` crate{1}",
crates[0], post))
})format!("and another `impl` found in the `{}` crate{post}", crates[0]));
904 }
905 _ => {
906 let span: MultiSpan = spans.into();
907 err.span_note(span, msg);
908 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("and more `impl`s found in the following crates: {0}{1}",
crate_names.join(", "), post))
})format!(
909 "and more `impl`s found in the following crates: {}{}",
910 crate_names.join(", "),
911 post,
912 ));
913 }
914 }
915 }
916}
917
918struct HasNumericInferVisitor;
919
920impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for HasNumericInferVisitor {
921 type Result = ControlFlow<()>;
922
923 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
924 if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Infer(ty::FloatVar(_) | ty::IntVar(_)) => true,
_ => false,
}matches!(ty.kind(), ty::Infer(ty::FloatVar(_) | ty::IntVar(_))) {
925 ControlFlow::Break(())
926 } else {
927 ControlFlow::Continue(())
928 }
929 }
930}