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::PrintPolyTraitClauseExt;
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::ClausePolarity::Positive)
71 | (ty::ImplPolarity::Negative, ty::ClausePolarity::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::PolyTraitClause<'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)) => {
186 data.trait_ref.args.terms().find(|term| term.has_non_region_infer())
187 }
188 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => data
189 .projection_term
190 .args
191 .terms()
192 .chain([data.term])
193 .find(|term| term.has_non_region_infer()),
194 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => Some(term),
195 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(data)) => {
196 data.walk().filter_map(ty::GenericArg::as_term).find(|term| term.is_infer())
197 }
198 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, _)) => Some(ct.into()),
199 ty::PredicateKind::Subtype(data) => Some(data.a.into()),
200 ty::PredicateKind::NormalizesTo(data) if data.term.is_infer() => Some(data.term),
201 _ => None,
202 }
203 }
204
205 {}
#[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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs"),
::tracing_core::__macro_support::Option::Some(205u32),
::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 /rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs:220",
"rustc_trait_selection::error_reporting::traits::ambiguity",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs"),
::tracing_core::__macro_support::Option::Some(220u32),
::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/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs:229",
"rustc_trait_selection::error_reporting::traits::ambiguity",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/cea272fa356e94bd2ee2cadf376630aa0683867a/compiler/rustc_trait_selection/src/error_reporting/traits/ambiguity.rs"),
::tracing_core::__macro_support::Option::Some(229u32),
::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")]
206 pub(super) fn maybe_report_ambiguity(
207 &self,
208 obligation: &PredicateObligation<'tcx>,
209 related: &[&FulfillmentError<'tcx>],
210 ) -> ErrorGuaranteed {
211 let predicate = self.resolve_vars_if_possible(obligation.predicate);
217 let span = obligation.cause.span;
218 let mut long_ty_path = None;
219
220 debug!(?predicate, obligation.cause.code = ?obligation.cause.code());
221
222 let bound_predicate = predicate.kind();
226 let mut err = match bound_predicate.skip_binder() {
227 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data)) => {
228 let trait_pred = bound_predicate.rebind(data);
229 debug!(?trait_pred);
230
231 if let Err(e) = predicate.error_reported() {
232 return e;
233 }
234
235 if let Err(guar) = self.tcx.ensure_result().coherent_trait(trait_pred.def_id()) {
236 return guar;
239 }
240
241 if matches!(
257 self.tcx.as_lang_item(trait_pred.def_id()),
258 Some(LangItem::Sized | LangItem::MetaSized)
259 ) {
260 return match self.tainted_by_errors() {
261 None => self
262 .emit_inference_failure_err(
263 obligation.cause.body_def_id,
264 span,
265 trait_pred.self_ty().skip_binder().into(),
266 TypeAnnotationNeeded::E0282,
267 false,
268 )
269 .emit(),
270 Some(e) => e,
271 };
272 }
273
274 let term = self.ambiguity_term(predicate);
288
289 let mut err = if let Some(term) = term {
290 let candidates: Vec<_> = self
291 .tcx
292 .all_impls(trait_pred.def_id())
293 .filter_map(|def_id| {
294 let imp = self.tcx.impl_trait_header(def_id);
295 if imp.polarity != ty::ImplPolarity::Positive
296 || !self.tcx.is_user_visible_dep(def_id.krate)
297 {
298 return None;
299 }
300 let imp = imp.trait_ref.skip_binder();
301 if imp
302 .with_replaced_self_ty(self.tcx, trait_pred.skip_binder().self_ty())
303 == trait_pred.skip_binder().trait_ref
304 {
305 Some(imp.self_ty())
306 } else {
307 None
308 }
309 })
310 .collect();
311 self.emit_inference_failure_err_with_type_hint(
312 obligation.cause.body_def_id,
313 span,
314 term,
315 TypeAnnotationNeeded::E0283,
316 true,
317 match &candidates[..] {
318 [candidate] => Some(*candidate),
319 _ => None,
320 },
321 )
322 } else {
323 struct_span_code_err!(
324 self.dcx(),
325 span,
326 E0283,
327 "type annotations needed: cannot satisfy `{}`",
328 self.tcx.short_string(predicate, &mut long_ty_path),
329 )
330 .with_long_ty_path(long_ty_path)
331 };
332
333 if let Some(ambiguities) = self.applicable_impls_to_mention(obligation, trait_pred)
334 {
335 if let Some(e) = self.tainted_by_errors()
336 && term.is_none()
337 {
338 err.cancel();
343 return e;
344 }
345 self.annotate_source_of_ambiguity(&mut err, &ambiguities, predicate);
346 } else {
347 if let Some(e) = self.tainted_by_errors() {
348 err.cancel();
349 return e;
350 }
351 if let Some(clause) = predicate.as_trait_clause()
352 && let ty::Infer(_) = clause.self_ty().skip_binder().kind()
353 {
354 let tr = self.tcx.short_string(
355 clause.print_modifiers_and_trait_path(),
356 &mut err.long_ty_path(),
357 );
358 err.note(format!("the type must implement `{tr}`"));
359 } else {
360 let pred = self.tcx.short_string(predicate, &mut err.long_ty_path());
361 err.note(format!("cannot satisfy `{pred}`"));
362 }
363 let impl_candidates =
364 self.find_similar_impl_candidates(predicate.as_trait_clause().unwrap());
365 if impl_candidates.len() < 40 {
366 self.report_similar_impl_candidates(
367 impl_candidates.as_slice(),
368 obligation,
369 trait_pred,
370 obligation.cause.body_def_id,
371 &mut err,
372 false,
373 obligation.param_env,
374 );
375 }
376 }
377
378 if let ObligationCauseCode::WhereClause(def_id, _)
379 | ObligationCauseCode::WhereClauseInExpr(def_id, ..) = *obligation.cause.code()
380 {
381 self.suggest_fully_qualified_path(&mut err, def_id, span, trait_pred.def_id());
382 }
383
384 if term.is_some_and(|term| term.as_type().is_some())
385 && let Some(body) =
386 self.tcx.hir_maybe_body_owned_by(obligation.cause.body_def_id)
387 {
388 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
389 expr_finder.visit_expr(&body.value);
390
391 if let Some(hir::Expr {
392 kind:
393 hir::ExprKind::Call(
394 hir::Expr {
395 kind: hir::ExprKind::Path(hir::QPath::Resolved(None, path)),
396 ..
397 },
398 _,
399 )
400 | hir::ExprKind::Path(hir::QPath::Resolved(None, path)),
401 ..
402 }) = expr_finder.result
403 && let [
404 ..,
405 trait_path_segment @ hir::PathSegment {
406 res: Res::Def(DefKind::Trait, trait_id),
407 ..
408 },
409 hir::PathSegment {
410 ident: assoc_item_ident,
411 res: Res::Def(_, item_id),
412 ..
413 },
414 ] = path.segments
415 && data.trait_ref.def_id == *trait_id
416 && self.tcx.trait_of_assoc(*item_id) == Some(*trait_id)
417 && let None = self.tainted_by_errors()
418 {
419 let assoc_item = self.tcx.associated_item(*item_id);
420 let (verb, noun) = match assoc_item.kind {
421 ty::AssocKind::Const { .. } => ("refer to the", "constant"),
422 ty::AssocKind::Fn { .. } => ("call", "function"),
423 ty::AssocKind::Type { .. } => ("refer to the", "type"),
426 };
427
428 err.cancel();
430 err = self.dcx().struct_span_err(
431 span,
432 format!(
433 "cannot {verb} associated {noun} on trait without specifying the \
434 corresponding `impl` type",
435 ),
436 );
437 err.code(E0790);
438
439 if item_id.is_local() {
440 let trait_ident = self.tcx.item_name(*trait_id);
441 err.span_label(
442 self.tcx.def_span(*item_id),
443 format!("`{trait_ident}::{assoc_item_ident}` defined here"),
444 );
445 }
446
447 err.span_label(span, format!("cannot {verb} associated {noun} of trait"));
448
449 let trait_impls = self.tcx.trait_impls_of(data.trait_ref.def_id);
450
451 if let Some(&impl_def_id) =
452 trait_impls.non_blanket_impls().values().flatten().next()
453 {
454 let non_blanket_impl_count =
455 trait_impls.non_blanket_impls().values().flatten().count();
456 let (message, self_types) = if non_blanket_impl_count == 1 {
459 (
460 "use the fully-qualified path to the only available \
461 implementation",
462 vec![format!(
463 "{}",
464 self.tcx
465 .type_of(impl_def_id)
466 .instantiate_identity()
467 .skip_norm_wip()
468 )],
469 )
470 } else if non_blanket_impl_count < 20 {
471 (
472 "use a fully-qualified path to one of the available \
473 implementations",
474 trait_impls
475 .non_blanket_impls()
476 .values()
477 .flatten()
478 .map(|&id| {
479 format!(
480 "{}",
481 self.tcx
482 .type_of(id)
483 .instantiate_identity()
484 .skip_norm_wip()
485 )
486 })
487 .collect::<Vec<String>>(),
488 )
489 } else {
490 (
491 "use a fully-qualified path to a specific available \
492 implementation",
493 vec!["/* self type */".to_string()],
494 )
495 };
496 let suggestions: Vec<_> = self_types
497 .into_iter()
498 .map(|self_type| {
499 let mut suggestions = vec![(
500 path.span.shrink_to_lo(),
501 format!("<{self_type} as "),
502 )];
503 if let Some(generic_arg) = trait_path_segment.args {
504 let between_span = trait_path_segment
505 .ident
506 .span
507 .between(generic_arg.span_ext);
508 suggestions.push((between_span, "".to_string()));
511 suggestions.push((
512 generic_arg.span_ext.shrink_to_hi(),
513 ">".to_string(),
514 ));
515 } else {
516 suggestions.push((
517 trait_path_segment.ident.span.shrink_to_hi(),
518 ">".to_string(),
519 ));
520 }
521 suggestions
522 })
523 .collect();
524 err.multipart_suggestions(
525 message,
526 suggestions,
527 Applicability::MaybeIncorrect,
528 );
529 }
530 }
531 };
532
533 err
534 }
535
536 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(term)) => {
537 if let Err(e) = term.error_reported() {
541 return e;
542 }
543 if let Some(e) = self.tainted_by_errors() {
544 return e;
545 }
546
547 self.emit_inference_failure_err(
548 obligation.cause.body_def_id,
549 span,
550 term,
551 TypeAnnotationNeeded::E0282,
552 false,
553 )
554 }
555
556 ty::PredicateKind::Subtype(data) => {
557 if let Err(e) = data.error_reported() {
558 return e;
559 }
560 if let Some(e) = self.tainted_by_errors() {
561 return e;
562 }
563 let ty::SubtypePredicate { a_is_expected: _, a, b } = data;
564 assert!(a.is_ty_var() && b.is_ty_var());
566 self.emit_inference_failure_err(
567 obligation.cause.body_def_id,
568 span,
569 a.into(),
570 TypeAnnotationNeeded::E0282,
571 true,
572 )
573 }
574
575 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
576 if let Err(e) = predicate.error_reported() {
577 return e;
578 }
579 if let Some(e) = self.tainted_by_errors() {
580 return e;
581 }
582
583 if data.projection_term.kind.is_trait_projection()
584 && let Err(guar) =
585 self.tcx.ensure_result().coherent_trait(self.tcx.parent(data.def_id()))
586 {
587 return guar;
590 }
591 let term = self.ambiguity_term(predicate);
592 let predicate = self.tcx.short_string(predicate, &mut long_ty_path);
593 if let Some(term) = term {
594 self.emit_inference_failure_err(
595 obligation.cause.body_def_id,
596 span,
597 term,
598 TypeAnnotationNeeded::E0284,
599 true,
600 )
601 .with_note(format!("cannot satisfy `{predicate}`"))
602 .with_long_ty_path(long_ty_path)
603 } else {
604 struct_span_code_err!(
606 self.dcx(),
607 span,
608 E0284,
609 "type annotations needed: cannot satisfy `{predicate}`",
610 )
611 .with_span_label(span, format!("cannot satisfy `{predicate}`"))
612 .with_long_ty_path(long_ty_path)
613 }
614 }
615
616 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(_)) => {
617 if let Err(e) = predicate.error_reported() {
618 return e;
619 }
620 if let Some(e) = self.tainted_by_errors() {
621 return e;
622 }
623 if let Some(term) = self.ambiguity_term(predicate) {
624 self.emit_inference_failure_err(
625 obligation.cause.body_def_id,
626 span,
627 term,
628 TypeAnnotationNeeded::E0284,
629 true,
630 )
631 } else {
632 let predicate = self.tcx.short_string(predicate, &mut long_ty_path);
634 struct_span_code_err!(
635 self.dcx(),
636 span,
637 E0284,
638 "type annotations needed: cannot satisfy `{predicate}`",
639 )
640 .with_span_label(span, format!("cannot satisfy `{predicate}`"))
641 .with_long_ty_path(long_ty_path)
642 }
643 }
644
645 ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType(ct, ..)) => self
646 .emit_inference_failure_err(
647 obligation.cause.body_def_id,
648 span,
649 ct.into(),
650 TypeAnnotationNeeded::E0284,
651 true,
652 ),
653
654 ty::PredicateKind::NormalizesTo(ty::NormalizesTo { alias, term })
655 if term.is_infer() =>
656 {
657 if let Some(e) = self.tainted_by_errors() {
658 return e;
659 }
660 let alias = self.tcx.short_string(alias, &mut long_ty_path);
661 struct_span_code_err!(
662 self.dcx(),
663 span,
664 E0284,
665 "type annotations needed: cannot normalize `{alias}`",
666 )
667 .with_span_label(span, format!("cannot normalize `{alias}`"))
668 .with_long_ty_path(long_ty_path)
669 }
670
671 ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature(sym)) => {
672 if let Some(e) = self.tainted_by_errors() {
673 return e;
674 }
675
676 if self.tcx.features().staged_api() {
677 self.dcx().struct_span_err(
678 span,
679 format!("unstable feature `{sym}` is used without being enabled."),
680 ).with_help(format!("The feature can be enabled by marking the current item with `#[unstable_feature_bound({sym})]`"))
681 } else {
682 feature_err_unstable_feature_bound(
683 &self.tcx.sess,
684 sym,
685 span,
686 format!("use of unstable library feature `{sym}`"),
687 )
688 }
689 }
690
691 _ => {
692 if let Some(e) = self.tainted_by_errors() {
693 return e;
694 }
695 let predicate = self.tcx.short_string(predicate, &mut long_ty_path);
696 struct_span_code_err!(
697 self.dcx(),
698 span,
699 E0284,
700 "type annotations needed: cannot satisfy `{predicate}`",
701 )
702 .with_span_label(span, format!("cannot satisfy `{predicate}`"))
703 .with_long_ty_path(long_ty_path)
704 }
705 };
706
707 let mut mentioned = vec![predicate];
712 let mut mentioned_strs: Vec<String> = vec![];
713 for &error in related {
714 let related_pred = self.resolve_vars_if_possible(error.obligation.predicate);
715 if mentioned.contains(&related_pred) {
716 continue;
717 }
718 let note = match related_pred.kind().skip_binder() {
719 ty::PredicateKind::Clause(ty::ClauseKind::Trait(data))
720 if !matches!(
721 self.tcx.as_lang_item(data.def_id()),
722 Some(LangItem::Sized | LangItem::MetaSized | LangItem::PointeeSized)
723 ) =>
724 {
725 let clause = related_pred.kind().rebind(data);
726 if let ty::Infer(_) = clause.self_ty().skip_binder().kind() {
727 let tr = self.tcx.short_string(
728 clause.print_modifiers_and_trait_path(),
729 &mut err.long_ty_path(),
730 );
731 format!("the type must also implement `{tr}`")
732 } else {
733 let pred = self.tcx.short_string(related_pred, &mut err.long_ty_path());
734 let note = format!("cannot satisfy `{pred}`");
735 if !mentioned_strs.contains(¬e)
743 && self.tainted_by_errors().is_none()
744 && let Some(ambiguities) =
745 self.applicable_impls_to_mention(&error.obligation, clause)
746 {
747 self.annotate_source_of_ambiguity(&mut err, &ambiguities, related_pred);
748 mentioned_strs.push(note);
749 mentioned.push(related_pred);
750 continue;
751 }
752 note
753 }
754 }
755 ty::PredicateKind::Clause(ty::ClauseKind::Projection(_)) => {
756 let pred = self.tcx.short_string(related_pred, &mut err.long_ty_path());
757 format!("cannot satisfy `{pred}`")
758 }
759 _ => {
760 mentioned.push(related_pred);
761 continue;
762 }
763 };
764 if !mentioned_strs.contains(¬e) {
767 err.note(note.clone());
768 mentioned_strs.push(note);
769 }
770 mentioned.push(related_pred);
771 }
772
773 self.note_obligation_cause(&mut err, obligation);
774 for &error in related {
778 if error.obligation.cause.code() != obligation.cause.code() {
779 self.note_obligation_cause(&mut err, &error.obligation);
780 }
781 }
782 err.emit()
783 }
784
785 fn applicable_impls_to_mention(
788 &self,
789 obligation: &PredicateObligation<'tcx>,
790 trait_pred: ty::PolyTraitClause<'tcx>,
791 ) -> Option<Vec<CandidateSource>> {
792 let mut ambiguities = compute_applicable_impls_for_diagnostics(
793 self.infcx,
794 &obligation.with(self.tcx, trait_pred),
795 false,
796 );
797 let has_non_region_infer =
798 trait_pred.skip_binder().trait_ref.args.types().any(|t| !t.is_ty_or_numeric_infer());
799 if ambiguities.len() > 5 {
803 let infcx = self.infcx;
804 if !ambiguities.iter().all(|option| match option {
805 CandidateSource::DefId(did) => infcx.tcx.generics_of(*did).count() == 0,
806 CandidateSource::ParamEnv(_) => true,
807 }) {
808 ambiguities.retain(|option| match option {
810 CandidateSource::DefId(did) => infcx.tcx.generics_of(*did).count() == 0,
811 CandidateSource::ParamEnv(_) => true,
812 });
813 }
814 }
815 (ambiguities.len() > 1 && ambiguities.len() < 10 && has_non_region_infer)
816 .then_some(ambiguities)
817 }
818
819 fn annotate_source_of_ambiguity(
820 &self,
821 err: &mut Diag<'_>,
822 ambiguities: &[CandidateSource],
823 predicate: ty::Predicate<'tcx>,
824 ) {
825 let mut spans = ::alloc::vec::Vec::new()vec![];
826 let mut crates = ::alloc::vec::Vec::new()vec![];
827 let mut post = ::alloc::vec::Vec::new()vec![];
828 let mut has_param_env = false;
829 for ambiguity in ambiguities {
830 match ambiguity {
831 CandidateSource::DefId(impl_def_id) => match self.tcx.span_of_impl(*impl_def_id) {
832 Ok(span) => spans.push(span),
833 Err(name) => {
834 crates.push(name);
835 if let Some(header) = to_pretty_impl_header(self.tcx, *impl_def_id) {
836 post.push(header);
837 }
838 }
839 },
840 CandidateSource::ParamEnv(span) => {
841 has_param_env = true;
842 spans.push(*span);
843 }
844 }
845 }
846 let mut crate_names: Vec<_> = crates.iter().map(|n| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", n))
})format!("`{n}`")).collect();
847 crate_names.sort();
848 crate_names.dedup();
849 post.sort();
850 post.dedup();
851
852 if self.tainted_by_errors().is_some()
853 && (crate_names.len() == 1
854 && spans.len() == 0
855 && ["`core`", "`alloc`", "`std`"].contains(&crate_names[0].as_str())
856 || predicate.visit_with(&mut HasNumericInferVisitor).is_break())
857 {
858 err.downgrade_to_delayed_bug();
864 return;
865 }
866
867 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!(
868 "multiple `impl`s{} satisfying `{}` found",
869 if has_param_env { " or `where` clauses" } else { "" },
870 predicate
871 );
872 let post = if post.len() > 1 || (post.len() == 1 && post[0].contains('\n')) {
873 ::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"))
874 } else if post.len() == 1 {
875 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": `{0}`", post[0]))
})format!(": `{}`", post[0])
876 } else {
877 String::new()
878 };
879
880 match (spans.len(), crates.len(), crate_names.len()) {
881 (0, 0, 0) => {
882 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot satisfy `{0}`", predicate))
})format!("cannot satisfy `{predicate}`"));
883 }
884 (0, _, 1) => {
885 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]));
886 }
887 (0, _, _) => {
888 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} in the following crates: {1}{2}",
msg, crate_names.join(", "), post))
})format!(
889 "{} in the following crates: {}{}",
890 msg,
891 crate_names.join(", "),
892 post,
893 ));
894 }
895 (_, 0, 0) => {
896 let span: MultiSpan = spans.into();
897 err.span_note(span, msg);
898 }
899 (_, 1, 1) => {
900 let span: MultiSpan = spans.into();
901 err.span_note(span, msg);
902 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]));
903 }
904 _ => {
905 let span: MultiSpan = spans.into();
906 err.span_note(span, msg);
907 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!(
908 "and more `impl`s found in the following crates: {}{}",
909 crate_names.join(", "),
910 post,
911 ));
912 }
913 }
914 }
915}
916
917struct HasNumericInferVisitor;
918
919impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for HasNumericInferVisitor {
920 type Result = ControlFlow<()>;
921
922 fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
923 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(_))) {
924 ControlFlow::Break(())
925 } else {
926 ControlFlow::Continue(())
927 }
928 }
929}