1pub mod ambiguity;
2pub mod call_kind;
3pub mod fulfillment_errors;
4pub mod on_unimplemented;
5mod overflow;
6pub mod suggestions;
7
8use std::{fmt, iter};
9
10use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
11use rustc_data_structures::unord::UnordSet;
12use rustc_errors::{Applicability, Diag, E0038, E0276, MultiSpan, struct_span_code_err};
13use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
14use rustc_hir::intravisit::Visitor;
15use rustc_hir::{self as hir, AmbigArg};
16use rustc_infer::traits::solve::Goal;
17use rustc_infer::traits::{
18 DynCompatibilityViolation, Obligation, ObligationCause, ObligationCauseCode,
19 PredicateObligation, SelectionError,
20};
21use rustc_middle::ty::print::{PrintTraitRefExt as _, with_no_trimmed_paths};
22use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt as _};
23use rustc_session::cstore::{ExternCrate, ExternCrateSource};
24use rustc_span::{DesugaringKind, ErrorGuaranteed, ExpnKind, Span};
25use tracing::{info, instrument};
26
27pub use self::overflow::*;
28use crate::error_reporting::TypeErrCtxt;
29use crate::traits::{FulfillmentError, FulfillmentErrorCode};
30
31#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CandidateSimilarity {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
CandidateSimilarity::Exact { ignoring_lifetimes: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Exact",
"ignoring_lifetimes", &__self_0),
CandidateSimilarity::Fuzzy { ignoring_lifetimes: __self_0 } =>
::core::fmt::Formatter::debug_struct_field1_finish(f, "Fuzzy",
"ignoring_lifetimes", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for CandidateSimilarity { }Copy, #[automatically_derived]
impl ::core::clone::Clone for CandidateSimilarity {
#[inline]
fn clone(&self) -> CandidateSimilarity {
let _: ::core::clone::AssertParamIsClone<bool>;
*self
}
}Clone, #[automatically_derived]
impl ::core::cmp::PartialEq for CandidateSimilarity {
#[inline]
fn eq(&self, other: &CandidateSimilarity) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(CandidateSimilarity::Exact { ignoring_lifetimes: __self_0 },
CandidateSimilarity::Exact { ignoring_lifetimes: __arg1_0 })
=> __self_0 == __arg1_0,
(CandidateSimilarity::Fuzzy { ignoring_lifetimes: __self_0 },
CandidateSimilarity::Fuzzy { ignoring_lifetimes: __arg1_0 })
=> __self_0 == __arg1_0,
_ => unsafe { ::core::intrinsics::unreachable() }
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for CandidateSimilarity {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<bool>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for CandidateSimilarity {
#[inline]
fn partial_cmp(&self, other: &CandidateSimilarity)
-> ::core::option::Option<::core::cmp::Ordering> {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
match (self, other) {
(CandidateSimilarity::Exact { ignoring_lifetimes: __self_0 },
CandidateSimilarity::Exact { ignoring_lifetimes: __arg1_0 })
=> ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0),
(CandidateSimilarity::Fuzzy { ignoring_lifetimes: __self_0 },
CandidateSimilarity::Fuzzy { ignoring_lifetimes: __arg1_0 })
=> ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0),
_ =>
::core::cmp::PartialOrd::partial_cmp(&__self_discr,
&__arg1_discr),
}
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for CandidateSimilarity {
#[inline]
fn cmp(&self, other: &CandidateSimilarity) -> ::core::cmp::Ordering {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
match ::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr) {
::core::cmp::Ordering::Equal =>
match (self, other) {
(CandidateSimilarity::Exact { ignoring_lifetimes: __self_0
}, CandidateSimilarity::Exact { ignoring_lifetimes: __arg1_0
}) => ::core::cmp::Ord::cmp(__self_0, __arg1_0),
(CandidateSimilarity::Fuzzy { ignoring_lifetimes: __self_0
}, CandidateSimilarity::Fuzzy { ignoring_lifetimes: __arg1_0
}) => ::core::cmp::Ord::cmp(__self_0, __arg1_0),
_ => unsafe { ::core::intrinsics::unreachable() }
},
cmp => cmp,
}
}
}Ord)]
36pub enum CandidateSimilarity {
37 Exact { ignoring_lifetimes: bool },
38 Fuzzy { ignoring_lifetimes: bool },
39}
40
41#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ImplCandidate<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "ImplCandidate",
"trait_ref", &self.trait_ref, "similarity", &self.similarity,
"impl_def_id", &&self.impl_def_id)
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::clone::Clone for ImplCandidate<'tcx> {
#[inline]
fn clone(&self) -> ImplCandidate<'tcx> {
let _: ::core::clone::AssertParamIsClone<ty::TraitRef<'tcx>>;
let _: ::core::clone::AssertParamIsClone<CandidateSimilarity>;
let _: ::core::clone::AssertParamIsClone<DefId>;
*self
}
}Clone, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for ImplCandidate<'tcx> { }Copy, #[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for ImplCandidate<'tcx> {
#[inline]
fn eq(&self, other: &ImplCandidate<'tcx>) -> bool {
self.trait_ref == other.trait_ref &&
self.similarity == other.similarity &&
self.impl_def_id == other.impl_def_id
}
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::cmp::Eq for ImplCandidate<'tcx> {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ty::TraitRef<'tcx>>;
let _: ::core::cmp::AssertParamIsEq<CandidateSimilarity>;
let _: ::core::cmp::AssertParamIsEq<DefId>;
}
}Eq)]
42pub struct ImplCandidate<'tcx> {
43 pub trait_ref: ty::TraitRef<'tcx>,
44 pub similarity: CandidateSimilarity,
45 impl_def_id: DefId,
46}
47
48enum GetSafeTransmuteErrorAndReason {
49 Silent,
50 Default,
51 Error { err_msg: String, safe_transmute_explanation: Option<String> },
52}
53
54pub struct FindExprBySpan<'hir> {
56 pub span: Span,
57 pub result: Option<&'hir hir::Expr<'hir>>,
58 pub ty_result: Option<&'hir hir::Ty<'hir>>,
59 pub include_closures: bool,
60 pub tcx: TyCtxt<'hir>,
61}
62
63impl<'hir> FindExprBySpan<'hir> {
64 pub fn new(span: Span, tcx: TyCtxt<'hir>) -> Self {
65 Self { span, result: None, ty_result: None, tcx, include_closures: false }
66 }
67}
68
69impl<'v> Visitor<'v> for FindExprBySpan<'v> {
70 type NestedFilter = rustc_middle::hir::nested_filter::OnlyBodies;
71
72 fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
73 self.tcx
74 }
75
76 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) {
77 if self.span == ex.span {
78 self.result = Some(ex);
79 } else {
80 if let hir::ExprKind::Closure(..) = ex.kind
81 && self.include_closures
82 && let closure_header_sp = self.span.with_hi(ex.span.hi())
83 && closure_header_sp == ex.span
84 {
85 self.result = Some(ex);
86 }
87 hir::intravisit::walk_expr(self, ex);
88 }
89 }
90
91 fn visit_ty(&mut self, ty: &'v hir::Ty<'v, AmbigArg>) {
92 if self.span == ty.span {
93 self.ty_result = Some(ty.as_unambig_ty());
94 } else {
95 hir::intravisit::walk_ty(self, ty);
96 }
97 }
98}
99
100#[derive(#[automatically_derived]
impl ::core::clone::Clone for ArgKind {
#[inline]
fn clone(&self) -> ArgKind {
match self {
ArgKind::Arg(__self_0, __self_1) =>
ArgKind::Arg(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
ArgKind::Tuple(__self_0, __self_1) =>
ArgKind::Tuple(::core::clone::Clone::clone(__self_0),
::core::clone::Clone::clone(__self_1)),
}
}
}Clone)]
102pub enum ArgKind {
103 Arg(String, String),
105
106 Tuple(Option<Span>, Vec<(String, String)>),
111}
112
113impl ArgKind {
114 fn empty() -> ArgKind {
115 ArgKind::Arg("_".to_owned(), "_".to_owned())
116 }
117
118 pub fn from_expected_ty(t: Ty<'_>, span: Option<Span>) -> ArgKind {
121 match t.kind() {
122 ty::Tuple(tys) => ArgKind::Tuple(
123 span,
124 tys.iter().map(|ty| ("_".to_owned(), ty.to_string())).collect::<Vec<_>>(),
125 ),
126 _ => ArgKind::Arg("_".to_owned(), t.to_string()),
127 }
128 }
129}
130
131#[derive(#[automatically_derived]
impl ::core::marker::Copy for DefIdOrName { }Copy, #[automatically_derived]
impl ::core::clone::Clone for DefIdOrName {
#[inline]
fn clone(&self) -> DefIdOrName {
let _: ::core::clone::AssertParamIsClone<DefId>;
let _: ::core::clone::AssertParamIsClone<&'static str>;
*self
}
}Clone)]
132pub enum DefIdOrName {
133 DefId(DefId),
134 Name(&'static str),
135}
136
137impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
138 pub fn report_fulfillment_errors(
139 &self,
140 mut errors: Vec<FulfillmentError<'tcx>>,
141 ) -> ErrorGuaranteed {
142 #[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for ErrorDescriptor<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"ErrorDescriptor", "goal", &self.goal, "index", &&self.index)
}
}Debug)]
143 struct ErrorDescriptor<'tcx> {
144 goal: Goal<'tcx, ty::Predicate<'tcx>>,
145 index: Option<usize>, }
147
148 let mut error_map: FxIndexMap<_, Vec<_>> = self
149 .reported_trait_errors
150 .borrow()
151 .iter()
152 .map(|(&span, goals)| {
153 (span, goals.0.iter().map(|&goal| ErrorDescriptor { goal, index: None }).collect())
154 })
155 .collect();
156
157 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for ErrorSortKey {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
ErrorSortKey::SubtypeFormat(__self_0, __self_1) =>
::core::fmt::Formatter::debug_tuple_field2_finish(f,
"SubtypeFormat", __self_0, &__self_1),
ErrorSortKey::OtherKind =>
::core::fmt::Formatter::write_str(f, "OtherKind"),
ErrorSortKey::SizedTrait =>
::core::fmt::Formatter::write_str(f, "SizedTrait"),
ErrorSortKey::MetaSizedTrait =>
::core::fmt::Formatter::write_str(f, "MetaSizedTrait"),
ErrorSortKey::PointeeSizedTrait =>
::core::fmt::Formatter::write_str(f, "PointeeSizedTrait"),
ErrorSortKey::Coerce =>
::core::fmt::Formatter::write_str(f, "Coerce"),
ErrorSortKey::WellFormed =>
::core::fmt::Formatter::write_str(f, "WellFormed"),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for ErrorSortKey {
#[inline]
fn eq(&self, other: &ErrorSortKey) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(ErrorSortKey::SubtypeFormat(__self_0, __self_1),
ErrorSortKey::SubtypeFormat(__arg1_0, __arg1_1)) =>
__self_0 == __arg1_0 && __self_1 == __arg1_1,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for ErrorSortKey {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<usize>;
}
}Eq, #[automatically_derived]
impl ::core::cmp::PartialOrd for ErrorSortKey {
#[inline]
fn partial_cmp(&self, other: &ErrorSortKey)
-> ::core::option::Option<::core::cmp::Ordering> {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
match (self, other) {
(ErrorSortKey::SubtypeFormat(__self_0, __self_1),
ErrorSortKey::SubtypeFormat(__arg1_0, __arg1_1)) =>
match ::core::cmp::PartialOrd::partial_cmp(__self_0, __arg1_0)
{
::core::option::Option::Some(::core::cmp::Ordering::Equal)
=> ::core::cmp::PartialOrd::partial_cmp(__self_1, __arg1_1),
cmp => cmp,
},
_ =>
::core::cmp::PartialOrd::partial_cmp(&__self_discr,
&__arg1_discr),
}
}
}PartialOrd, #[automatically_derived]
impl ::core::cmp::Ord for ErrorSortKey {
#[inline]
fn cmp(&self, other: &ErrorSortKey) -> ::core::cmp::Ordering {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
match ::core::cmp::Ord::cmp(&__self_discr, &__arg1_discr) {
::core::cmp::Ordering::Equal =>
match (self, other) {
(ErrorSortKey::SubtypeFormat(__self_0, __self_1),
ErrorSortKey::SubtypeFormat(__arg1_0, __arg1_1)) =>
match ::core::cmp::Ord::cmp(__self_0, __arg1_0) {
::core::cmp::Ordering::Equal =>
::core::cmp::Ord::cmp(__self_1, __arg1_1),
cmp => cmp,
},
_ => ::core::cmp::Ordering::Equal,
},
cmp => cmp,
}
}
}Ord)]
162 enum ErrorSortKey {
163 SubtypeFormat(usize, usize),
164 OtherKind,
165 SizedTrait,
166 MetaSizedTrait,
167 PointeeSizedTrait,
168 Coerce,
169 WellFormed,
170 }
171 errors.sort_by_key(|e| {
172 let maybe_sizedness_did = match e.obligation.predicate.kind().skip_binder() {
173 ty::PredicateKind::Clause(ty::ClauseKind::Trait(pred)) => Some(pred.def_id()),
174 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(pred)) => Some(pred.def_id()),
175 _ => None,
176 };
177
178 match e.obligation.predicate.kind().skip_binder() {
179 ty::PredicateKind::Subtype(_)
180 if #[allow(non_exhaustive_omitted_patterns)] match e.obligation.cause.span.desugaring_kind()
{
Some(DesugaringKind::FormatLiteral { .. }) => true,
_ => false,
}matches!(
181 e.obligation.cause.span.desugaring_kind(),
182 Some(DesugaringKind::FormatLiteral { .. })
183 ) =>
184 {
185 let (_, row, col, ..) =
186 self.tcx.sess.source_map().span_to_location_info(e.obligation.cause.span);
187 ErrorSortKey::SubtypeFormat(row, col)
188 }
189 _ if maybe_sizedness_did == self.tcx.lang_items().sized_trait() => {
190 ErrorSortKey::SizedTrait
191 }
192 _ if maybe_sizedness_did == self.tcx.lang_items().meta_sized_trait() => {
193 ErrorSortKey::MetaSizedTrait
194 }
195 _ if maybe_sizedness_did == self.tcx.lang_items().pointee_sized_trait() => {
196 ErrorSortKey::PointeeSizedTrait
197 }
198 ty::PredicateKind::Coerce(_) => ErrorSortKey::Coerce,
199 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(_)) => {
200 ErrorSortKey::WellFormed
201 }
202 _ => ErrorSortKey::OtherKind,
203 }
204 });
205
206 for (index, error) in errors.iter().enumerate() {
207 let mut span = error.obligation.cause.span;
210 let expn_data = span.ctxt().outer_expn_data();
211 if let ExpnKind::Desugaring(_) = expn_data.kind {
212 span = expn_data.call_site;
213 }
214
215 error_map
216 .entry(span)
217 .or_default()
218 .push(ErrorDescriptor { goal: error.obligation.as_goal(), index: Some(index) });
219 }
220
221 let mut is_suppressed = ::alloc::vec::from_elem(false, errors.len())vec![false; errors.len()];
224 for (_, error_set) in error_map.iter() {
225 for error in error_set {
227 if let Some(index) = error.index {
228 for error2 in error_set {
232 if error2.index.is_some_and(|index2| is_suppressed[index2]) {
233 continue;
237 }
238
239 if self.error_implies(error2.goal, error.goal)
240 && !(error2.index >= error.index
241 && self.error_implies(error.goal, error2.goal))
242 {
243 {
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/mod.rs:243",
"rustc_trait_selection::error_reporting::traits",
::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(243u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::INFO <=
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("skipping {0:?} (implied by {1:?})",
error, error2) as &dyn Value))])
});
} else { ; }
};info!("skipping {:?} (implied by {:?})", error, error2);
244 is_suppressed[index] = true;
245 break;
246 }
247 }
248 }
249 }
250 }
251
252 let mut reported = None;
253 for from_expansion in [false, true] {
254 for (error, suppressed) in iter::zip(&errors, &is_suppressed) {
255 if !suppressed && error.obligation.cause.span.from_expansion() == from_expansion {
256 if !error.references_error() {
257 let guar = self.report_fulfillment_error(error);
258 self.infcx.set_tainted_by_errors(guar);
259 reported = Some(guar);
260 let mut span = error.obligation.cause.span;
263 let expn_data = span.ctxt().outer_expn_data();
264 if let ExpnKind::Desugaring(_) = expn_data.kind {
265 span = expn_data.call_site;
266 }
267 self.reported_trait_errors
268 .borrow_mut()
269 .entry(span)
270 .or_insert_with(|| (::alloc::vec::Vec::new()vec![], guar))
271 .0
272 .push(error.obligation.as_goal());
273 }
274 if let Some(guar) = self.dcx().has_errors() {
275 self.infcx.set_tainted_by_errors(guar);
276 }
277 }
278 }
279 }
280
281 reported.unwrap_or_else(|| self.dcx().delayed_bug("failed to report fulfillment errors"))
285 }
286
287 #[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("report_fulfillment_error",
"rustc_trait_selection::error_reporting::traits",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/mod.rs"),
::tracing_core::__macro_support::Option::Some(287u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits"),
::tracing_core::field::FieldSet::new(&["error"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&error)
as &dyn 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 mut error =
FulfillmentError {
obligation: error.obligation.clone(),
code: error.code.clone(),
root_obligation: error.root_obligation.clone(),
};
if #[allow(non_exhaustive_omitted_patterns)] match error.code {
FulfillmentErrorCode::Select(crate::traits::SelectionError::Unimplemented)
| FulfillmentErrorCode::Project(_) => true,
_ => false,
} && self.apply_do_not_recommend(&mut error.obligation) {
error.code =
FulfillmentErrorCode::Select(SelectionError::Unimplemented);
}
match error.code {
FulfillmentErrorCode::Select(ref selection_error) =>
self.report_selection_error(error.obligation.clone(),
&error.root_obligation, selection_error),
FulfillmentErrorCode::Project(ref e) => {
self.report_projection_error(&error.obligation, e)
}
FulfillmentErrorCode::Ambiguity { overflow: None } => {
self.maybe_report_ambiguity(&error.obligation)
}
FulfillmentErrorCode::Ambiguity {
overflow: Some(suggest_increasing_limit) } => {
self.report_overflow_no_abort(error.obligation.clone(),
suggest_increasing_limit)
}
FulfillmentErrorCode::Subtype(ref expected_found, ref err) =>
self.report_mismatched_types(&error.obligation.cause,
error.obligation.param_env, expected_found.expected,
expected_found.found, *err).emit(),
FulfillmentErrorCode::ConstEquate(ref expected_found, ref err)
=> {
let mut diag =
self.report_mismatched_consts(&error.obligation.cause,
error.obligation.param_env, expected_found.expected,
expected_found.found, *err);
let code =
error.obligation.cause.code().peel_derives().peel_match_impls();
if let ObligationCauseCode::WhereClause(..) |
ObligationCauseCode::WhereClauseInExpr(..) = code {
self.note_obligation_cause_code(error.obligation.cause.body_id,
&mut diag, error.obligation.predicate,
error.obligation.param_env, code,
&mut ::alloc::vec::Vec::new(), &mut Default::default());
}
diag.emit()
}
FulfillmentErrorCode::Cycle(ref cycle) =>
self.report_overflow_obligation_cycle(cycle),
}
}
}
}#[instrument(skip(self), level = "debug")]
288 fn report_fulfillment_error(&self, error: &FulfillmentError<'tcx>) -> ErrorGuaranteed {
289 let mut error = FulfillmentError {
290 obligation: error.obligation.clone(),
291 code: error.code.clone(),
292 root_obligation: error.root_obligation.clone(),
293 };
294 if matches!(
295 error.code,
296 FulfillmentErrorCode::Select(crate::traits::SelectionError::Unimplemented)
297 | FulfillmentErrorCode::Project(_)
298 ) && self.apply_do_not_recommend(&mut error.obligation)
299 {
300 error.code = FulfillmentErrorCode::Select(SelectionError::Unimplemented);
301 }
302
303 match error.code {
304 FulfillmentErrorCode::Select(ref selection_error) => self.report_selection_error(
305 error.obligation.clone(),
306 &error.root_obligation,
307 selection_error,
308 ),
309 FulfillmentErrorCode::Project(ref e) => {
310 self.report_projection_error(&error.obligation, e)
311 }
312 FulfillmentErrorCode::Ambiguity { overflow: None } => {
313 self.maybe_report_ambiguity(&error.obligation)
314 }
315 FulfillmentErrorCode::Ambiguity { overflow: Some(suggest_increasing_limit) } => {
316 self.report_overflow_no_abort(error.obligation.clone(), suggest_increasing_limit)
317 }
318 FulfillmentErrorCode::Subtype(ref expected_found, ref err) => self
319 .report_mismatched_types(
320 &error.obligation.cause,
321 error.obligation.param_env,
322 expected_found.expected,
323 expected_found.found,
324 *err,
325 )
326 .emit(),
327 FulfillmentErrorCode::ConstEquate(ref expected_found, ref err) => {
328 let mut diag = self.report_mismatched_consts(
329 &error.obligation.cause,
330 error.obligation.param_env,
331 expected_found.expected,
332 expected_found.found,
333 *err,
334 );
335 let code = error.obligation.cause.code().peel_derives().peel_match_impls();
336 if let ObligationCauseCode::WhereClause(..)
337 | ObligationCauseCode::WhereClauseInExpr(..) = code
338 {
339 self.note_obligation_cause_code(
340 error.obligation.cause.body_id,
341 &mut diag,
342 error.obligation.predicate,
343 error.obligation.param_env,
344 code,
345 &mut vec![],
346 &mut Default::default(),
347 );
348 }
349 diag.emit()
350 }
351 FulfillmentErrorCode::Cycle(ref cycle) => self.report_overflow_obligation_cycle(cycle),
352 }
353 }
354
355 fn extern_crates_with_the_same_name(
359 &self,
360 expected_def_id: DefId,
361 trait_def_id: DefId,
362 ) -> bool {
363 if expected_def_id.is_local() || trait_def_id.is_local() {
364 return false;
365 }
366 match (
370 self.tcx.extern_crate(expected_def_id.krate),
371 self.tcx.extern_crate(trait_def_id.krate),
372 ) {
373 (
374 Some(&ExternCrate {
375 src: ExternCrateSource::Extern(expected_def_id),
376 dependency_of: LOCAL_CRATE,
377 ..
378 }),
379 Some(&ExternCrate {
380 src: ExternCrateSource::Extern(trait_def_id),
381 dependency_of: LOCAL_CRATE,
382 ..
383 }),
384 ) => self.tcx.item_name(expected_def_id) == self.tcx.item_name(trait_def_id),
385 _ => false,
386 }
387 }
388
389 pub fn check_same_definition_different_crate<F>(
390 &self,
391 err: &mut Diag<'_>,
392 expected_did: DefId,
393 found_dids: impl Iterator<Item = DefId>,
394 get_impls: F,
395 ty: &str,
396 ) -> bool
397 where
398 F: Fn(DefId) -> Vec<Span>,
399 {
400 let krate = self.tcx.crate_name(expected_did.krate);
401 let name = self.tcx.item_name(expected_did);
402 let definitions_with_same_path: UnordSet<_> = found_dids
403 .filter(|&def_id| {
404 def_id.krate != expected_did.krate
405 && (self.extern_crates_with_the_same_name(expected_did, def_id)
406 || self.tcx.crate_name(def_id.krate) == krate)
407 && self.tcx.item_name(def_id) == name
408 })
409 .map(|def_id| (self.tcx.def_path_str(def_id), def_id))
410 .collect();
411
412 let definitions_with_same_path =
413 definitions_with_same_path.into_items().into_sorted_stable_ord_by_key(|(p, _)| p);
414 let mut suggested = false;
415 let mut trait_is_impl = false;
416
417 if !definitions_with_same_path.is_empty() {
418 let mut span: MultiSpan = self.tcx.def_span(expected_did).into();
419 span.push_span_label(
420 self.tcx.def_span(expected_did),
421 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this is the expected {0}", ty))
})format!("this is the expected {ty}"),
422 );
423 suggested = true;
424 for (_, definition_with_same_path) in &definitions_with_same_path {
425 let definitions_impls = get_impls(*definition_with_same_path);
426 if definitions_impls.is_empty() {
427 continue;
428 }
429
430 for candidate_span in definitions_impls {
431 span.push_span_label(candidate_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this is the found {0}", ty))
})format!("this is the found {ty}"));
432 trait_is_impl = true;
433 }
434 }
435 if !trait_is_impl {
436 for (_, def_id) in definitions_with_same_path {
437 span.push_span_label(
438 self.tcx.def_span(def_id),
439 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this is the {0} that was imported",
ty))
})format!("this is the {ty} that was imported"),
440 );
441 }
442 }
443 self.note_two_crate_versions(expected_did.krate, span, err);
444 err.help("you can use `cargo tree` to explore your dependency tree");
445 }
446 suggested
447 }
448}
449
450pub(crate) fn to_pretty_impl_header(tcx: TyCtxt<'_>, impl_def_id: DefId) -> Option<String> {
453 use std::fmt::Write;
454
455 let trait_ref = tcx.impl_opt_trait_ref(impl_def_id)?.instantiate_identity();
456 let mut w = "impl".to_owned();
457
458 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for SizednessFound {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"SizednessFound", "sized", &self.sized, "meta_sized",
&&self.meta_sized)
}
}Debug, #[automatically_derived]
impl ::core::default::Default for SizednessFound {
#[inline]
fn default() -> SizednessFound {
SizednessFound {
sized: ::core::default::Default::default(),
meta_sized: ::core::default::Default::default(),
}
}
}Default)]
459 struct SizednessFound {
460 sized: bool,
461 meta_sized: bool,
462 }
463
464 let mut types_with_sizedness_bounds = FxIndexMap::<_, SizednessFound>::default();
465
466 let args = ty::GenericArgs::identity_for_item(tcx, impl_def_id);
467
468 let arg_names = args.iter().map(|k| k.to_string()).filter(|k| k != "'_").collect::<Vec<_>>();
469 if !arg_names.is_empty() {
470 w.push('<');
471 w.push_str(&arg_names.join(", "));
472 w.push('>');
473
474 for ty in args.types() {
475 types_with_sizedness_bounds.insert(ty, SizednessFound::default());
477 }
478 }
479
480 w.write_fmt(format_args!(" {0}{1} for {2}",
tcx.impl_polarity(impl_def_id).as_str(),
trait_ref.print_only_trait_path(),
tcx.type_of(impl_def_id).instantiate_identity()))write!(
481 w,
482 " {}{} for {}",
483 tcx.impl_polarity(impl_def_id).as_str(),
484 trait_ref.print_only_trait_path(),
485 tcx.type_of(impl_def_id).instantiate_identity()
486 )
487 .unwrap();
488
489 let predicates = tcx.predicates_of(impl_def_id).predicates;
490 let mut pretty_predicates = Vec::with_capacity(predicates.len());
491
492 let sized_trait = tcx.lang_items().sized_trait();
493 let meta_sized_trait = tcx.lang_items().meta_sized_trait();
494
495 for (p, _) in predicates {
496 if let Some(trait_clause) = p.as_trait_clause() {
498 let self_ty = trait_clause.self_ty().skip_binder();
499 let sizedness_of = types_with_sizedness_bounds.entry(self_ty).or_default();
500 if Some(trait_clause.def_id()) == sized_trait {
501 sizedness_of.sized = true;
502 continue;
503 } else if Some(trait_clause.def_id()) == meta_sized_trait {
504 sizedness_of.meta_sized = true;
505 continue;
506 }
507 }
508
509 pretty_predicates.push(p.to_string());
510 }
511
512 for (ty, sizedness) in types_with_sizedness_bounds {
513 if !tcx.features().sized_hierarchy() {
514 if sizedness.sized {
515 } else {
517 pretty_predicates.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ?Sized", ty))
})format!("{ty}: ?Sized"));
518 }
519 } else {
520 if sizedness.sized {
521 pretty_predicates.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: Sized", ty))
})format!("{ty}: Sized"));
523 } else if sizedness.meta_sized {
524 pretty_predicates.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: MetaSized", ty))
})format!("{ty}: MetaSized"));
525 } else {
526 pretty_predicates.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: PointeeSized", ty))
})format!("{ty}: PointeeSized"));
527 }
528 }
529 }
530
531 if !pretty_predicates.is_empty() {
532 w.write_fmt(format_args!("\n where {0}", pretty_predicates.join(", ")))write!(w, "\n where {}", pretty_predicates.join(", ")).unwrap();
533 }
534
535 w.push(';');
536 Some(w)
537}
538
539impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
540 pub fn report_extra_impl_obligation(
541 &self,
542 error_span: Span,
543 impl_item_def_id: LocalDefId,
544 trait_item_def_id: DefId,
545 requirement: &dyn fmt::Display,
546 ) -> Diag<'a> {
547 let mut err = {
self.dcx().struct_span_err(error_span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("impl has stricter requirements than trait"))
})).with_code(E0276)
}struct_span_code_err!(
548 self.dcx(),
549 error_span,
550 E0276,
551 "impl has stricter requirements than trait"
552 );
553
554 if !self.tcx.is_impl_trait_in_trait(trait_item_def_id) {
555 if let Some(span) = self.tcx.hir_span_if_local(trait_item_def_id) {
556 let item_name = self.tcx.item_name(impl_item_def_id.to_def_id());
557 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("definition of `{0}` from trait",
item_name))
})format!("definition of `{item_name}` from trait"));
558 }
559 }
560
561 err.span_label(error_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("impl has extra requirement {0}",
requirement))
})format!("impl has extra requirement {requirement}"));
562
563 err
564 }
565}
566
567pub fn report_dyn_incompatibility<'tcx>(
568 tcx: TyCtxt<'tcx>,
569 span: Span,
570 hir_id: Option<hir::HirId>,
571 trait_def_id: DefId,
572 violations: &[DynCompatibilityViolation],
573) -> Diag<'tcx> {
574 let trait_str = tcx.def_path_str(trait_def_id);
575 let trait_span = tcx.hir_get_if_local(trait_def_id).and_then(|node| match node {
576 hir::Node::Item(item) => match item.kind {
577 hir::ItemKind::Trait(_, _, _, ident, ..)
578 | hir::ItemKind::TraitAlias(_, ident, _, _) => Some(ident.span),
579 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
580 },
581 _ => None,
582 });
583
584 let mut err = {
tcx.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the {0} `{1}` is not dyn compatible",
tcx.def_descr(trait_def_id), trait_str))
})).with_code(E0038)
}struct_span_code_err!(
585 tcx.dcx(),
586 span,
587 E0038,
588 "the {} `{}` is not dyn compatible",
589 tcx.def_descr(trait_def_id),
590 trait_str
591 );
592 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is not dyn compatible",
trait_str))
})format!("`{trait_str}` is not dyn compatible"));
593
594 attempt_dyn_to_impl_suggestion(tcx, hir_id, &mut err);
595
596 let mut reported_violations = FxIndexSet::default();
597 let mut multi_span = ::alloc::vec::Vec::new()vec![];
598 let mut messages = ::alloc::vec::Vec::new()vec![];
599 for violation in violations {
600 if let DynCompatibilityViolation::SizedSelf(sp) = &violation
601 && !sp.is_empty()
602 {
603 reported_violations.insert(DynCompatibilityViolation::SizedSelf(::alloc::vec::Vec::new()vec![].into()));
606 }
607 if reported_violations.insert(violation.clone()) {
608 let spans = violation.spans();
609 let msg = if trait_span.is_none() || spans.is_empty() {
610 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait is not dyn compatible because {0}",
violation.error_msg()))
})format!("the trait is not dyn compatible because {}", violation.error_msg())
611 } else {
612 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("...because {0}",
violation.error_msg()))
})format!("...because {}", violation.error_msg())
613 };
614 if spans.is_empty() {
615 err.note(msg);
616 } else {
617 for span in spans {
618 multi_span.push(span);
619 messages.push(msg.clone());
620 }
621 }
622 }
623 }
624 let has_multi_span = !multi_span.is_empty();
625 let mut note_span = MultiSpan::from_spans(multi_span.clone());
626 if let (Some(trait_span), true) = (trait_span, has_multi_span) {
627 note_span.push_span_label(trait_span, "this trait is not dyn compatible...");
628 }
629 for (span, msg) in iter::zip(multi_span, messages) {
630 note_span.push_span_label(span, msg);
631 }
632 err.span_note(
633 note_span,
634 "for a trait to be dyn compatible it needs to allow building a vtable\n\
635 for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>",
636 );
637
638 if trait_span.is_some() {
640 let mut potential_solutions: Vec<_> =
641 reported_violations.into_iter().map(|violation| violation.solution()).collect();
642 potential_solutions.sort();
643 potential_solutions.dedup();
645 for solution in potential_solutions {
646 solution.add_to(&mut err);
647 }
648 }
649
650 attempt_dyn_to_enum_suggestion(tcx, trait_def_id, &*trait_str, &mut err);
651
652 err
653}
654
655fn attempt_dyn_to_enum_suggestion(
658 tcx: TyCtxt<'_>,
659 trait_def_id: DefId,
660 trait_str: &str,
661 err: &mut Diag<'_>,
662) {
663 let impls_of = tcx.trait_impls_of(trait_def_id);
664
665 if !impls_of.blanket_impls().is_empty() {
666 return;
667 }
668
669 let concrete_impls: Option<Vec<Ty<'_>>> = impls_of
670 .non_blanket_impls()
671 .values()
672 .flatten()
673 .map(|impl_id| {
674 let Some(impl_type) = tcx.type_of(*impl_id).no_bound_vars() else { return None };
677
678 match impl_type.kind() {
683 ty::Str | ty::Slice(_) | ty::Dynamic(_, _) => {
684 return None;
685 }
686 _ => {}
687 }
688 Some(impl_type)
689 })
690 .collect();
691 let Some(concrete_impls) = concrete_impls else { return };
692
693 const MAX_IMPLS_TO_SUGGEST_CONVERTING_TO_ENUM: usize = 9;
694 if concrete_impls.is_empty() || concrete_impls.len() > MAX_IMPLS_TO_SUGGEST_CONVERTING_TO_ENUM {
695 return;
696 }
697
698 let externally_visible = if let Some(def_id) = trait_def_id.as_local() {
699 tcx.resolutions(()).effective_visibilities.is_exported(def_id)
703 } else {
704 false
705 };
706
707 if let [only_impl] = &concrete_impls[..] {
708 let within = if externally_visible { " within this crate" } else { "" };
709 err.help({
let _guard = NoTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("only type `{0}` implements `{1}`{2}; consider using it directly instead.",
only_impl, trait_str, within))
})
}with_no_trimmed_paths!(format!(
710 "only type `{only_impl}` implements `{trait_str}`{within}; \
711 consider using it directly instead."
712 )));
713 } else {
714 let types = concrete_impls
715 .iter()
716 .map(|t| {
let _guard = NoTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {0}", t))
})
}with_no_trimmed_paths!(format!(" {}", t)))
717 .collect::<Vec<String>>()
718 .join("\n");
719
720 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following types implement `{0}`:\n{1}\nconsider defining an enum where each variant holds one of these types,\nimplementing `{0}` for this new enum and using it instead",
trait_str, types))
})format!(
721 "the following types implement `{trait_str}`:\n\
722 {types}\n\
723 consider defining an enum where each variant holds one of these types,\n\
724 implementing `{trait_str}` for this new enum and using it instead",
725 ));
726 }
727
728 if externally_visible {
729 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` may be implemented in other crates; if you want to support your users passing their own types here, you can\'t refer to a specific type",
trait_str))
})format!(
730 "`{trait_str}` may be implemented in other crates; if you want to support your users \
731 passing their own types here, you can't refer to a specific type",
732 ));
733 }
734}
735
736fn attempt_dyn_to_impl_suggestion(tcx: TyCtxt<'_>, hir_id: Option<hir::HirId>, err: &mut Diag<'_>) {
739 let Some(hir_id) = hir_id else { return };
740 let hir::Node::Ty(ty) = tcx.hir_node(hir_id) else { return };
741 let hir::TyKind::TraitObject([trait_ref, ..], ..) = ty.kind else { return };
742
743 let Some((_id, first_non_type_parent_node)) =
748 tcx.hir_parent_iter(hir_id).find(|(_id, node)| !#[allow(non_exhaustive_omitted_patterns)] match node {
hir::Node::Ty(_) => true,
_ => false,
}matches!(node, hir::Node::Ty(_)))
749 else {
750 return;
751 };
752 if first_non_type_parent_node.fn_sig().is_none() {
753 return;
754 }
755
756 err.span_suggestion_verbose(
757 ty.span.until(trait_ref.span),
758 "consider using an opaque type instead",
759 "impl ",
760 Applicability::MaybeIncorrect,
761 );
762}