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