1use rustc_errors::Applicability::{MachineApplicable, MaybeIncorrect};
2use rustc_errors::{Diag, MultiSpan, pluralize};
3use rustc_hir::def::DefKind;
4use rustc_hir::{self as hir, LangItem, find_attr};
5use rustc_middle::traits::{ObligationCause, ObligationCauseCode};
6use rustc_middle::ty::error::{ExpectedFound, TypeError};
7use rustc_middle::ty::fast_reject::DeepRejectCtxt;
8use rustc_middle::ty::print::{FmtPrinter, Printer};
9use rustc_middle::ty::{self, Ty, suggest_constraining_type_param};
10use rustc_span::def_id::DefId;
11use rustc_span::{BytePos, Span, Symbol};
12use tracing::debug;
13
14use crate::error_reporting::TypeErrCtxt;
15use crate::infer::InferCtxtExt;
16
17impl<'tcx> TypeErrCtxt<'_, 'tcx> {
18 pub fn note_and_explain_type_err(
19 &self,
20 diag: &mut Diag<'_>,
21 err: TypeError<'tcx>,
22 cause: &ObligationCause<'tcx>,
23 sp: Span,
24 body_owner_def_id: Option<DefId>,
25 ) {
26 {
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/infer/note_and_explain.rs:26",
"rustc_trait_selection::error_reporting::infer::note_and_explain",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs"),
::tracing_core::__macro_support::Option::Some(26u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::note_and_explain"),
::tracing_core::field::FieldSet::new(&["message"],
::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};
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!("note_and_explain_type_err err={0:?} cause={1:?}",
err, cause) as &dyn Value))])
});
} else { ; }
};debug!("note_and_explain_type_err err={:?} cause={:?}", err, cause);
27
28 let tcx = self.tcx;
29
30 let body_generics = body_owner_def_id.map(|def_id| tcx.generics_of(def_id));
31
32 match err {
33 TypeError::ArgumentSorts(values, _) | TypeError::Sorts(values) => {
34 match (*values.expected.kind(), *values.found.kind()) {
35 (ty::Closure(..), ty::Closure(..)) => {
36 diag.note("no two closures, even if identical, have the same type");
37 diag.help("consider boxing your closure and/or using it as a trait object");
38 }
39 (ty::Coroutine(def_id1, ..), ty::Coroutine(def_id2, ..))
40 if self.tcx.coroutine_is_async(def_id1)
41 && self.tcx.coroutine_is_async(def_id2) =>
42 {
43 diag.note("no two async blocks, even if identical, have the same type");
44 diag.help(
45 "consider pinning your async block and casting it to a trait object",
46 );
47 }
48 (
49 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }),
50 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }),
51 ) => {
52 diag.note("distinct uses of `impl Trait` result in different opaque types");
54 }
55 (ty::Float(_), ty::Infer(ty::IntVar(_)))
56 if let Ok(
57 snippet,
59 ) = tcx.sess.source_map().span_to_snippet(sp) =>
60 {
61 if snippet.chars().all(|c| c.is_digit(10) || c == '-' || c == '_') {
62 diag.span_suggestion_verbose(
63 sp.shrink_to_hi(),
64 "use a float literal",
65 ".0",
66 MachineApplicable,
67 );
68 }
69 }
70 (ty::Param(expected), ty::Param(found)) => {
71 if let Some(generics) = body_generics {
72 let e_span = tcx.def_span(generics.type_param(expected, tcx).def_id);
73 if !sp.contains(e_span) {
74 diag.span_label(e_span, "expected type parameter");
75 }
76 let f_span = tcx.def_span(generics.type_param(found, tcx).def_id);
77 if !sp.contains(f_span) {
78 diag.span_label(f_span, "found type parameter");
79 }
80 }
81 diag.note(
82 "a type parameter was expected, but a different one was found; \
83 you might be missing a type parameter or trait bound",
84 );
85 diag.note(
86 "for more information, visit \
87 https://doc.rust-lang.org/book/ch10-02-traits.html\
88 #traits-as-parameters",
89 );
90 }
91 (
92 ty::Alias(
93 _,
94 ty::AliasTy {
95 kind: ty::Projection { .. } | ty::Inherent { .. }, ..
96 },
97 ),
98 ty::Alias(
99 _,
100 ty::AliasTy {
101 kind: ty::Projection { .. } | ty::Inherent { .. }, ..
102 },
103 ),
104 ) => {
105 diag.note("an associated type was expected, but a different one was found");
106 }
107 (
109 ty::Param(p),
110 ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { def_id }, .. }),
111 )
112 | (
113 ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { def_id }, .. }),
114 ty::Param(p),
115 ) if !tcx.is_impl_trait_in_trait(def_id)
116 && let Some(generics) = body_generics =>
117 {
118 let param = generics.type_param(p, tcx);
119 let p_def_id = param.def_id;
120 let p_span = tcx.def_span(p_def_id);
121 let expected = match (values.expected.kind(), values.found.kind()) {
122 (ty::Param(_), _) => "expected ",
123 (_, ty::Param(_)) => "found ",
124 _ => "",
125 };
126 if !sp.contains(p_span) {
127 diag.span_label(p_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}this type parameter", expected))
})format!("{expected}this type parameter"));
128 }
129 let param_def_id = match *proj.self_ty().kind() {
130 ty::Param(param) => generics.type_param(param, tcx).def_id,
131 _ => p_def_id,
132 };
133 let parent = param_def_id.as_local().and_then(|id| {
134 let local_id = tcx.local_def_id_to_hir_id(id);
135 let generics = tcx.parent_hir_node(local_id).generics()?;
136 Some((id, generics))
137 });
138 let mut note = true;
139 if let Some((local_id, generics)) = parent {
140 let (trait_ref, assoc_args) = proj.trait_ref_and_own_args(tcx);
143 let item_name = tcx.item_name(def_id);
144 let item_args = self.format_generic_args(assoc_args);
145
146 if
147 (tcx.is_lang_item(trait_ref.def_id, LangItem::AsyncFnOnce)
151 && tcx.is_lang_item(def_id, LangItem::CallOnceFuture))
152 ||
154 (tcx.is_lang_item(trait_ref.def_id, LangItem::AsyncFnMut)
155 && tcx.is_lang_item(def_id, LangItem::CallRefFuture))
156 ||
158 (tcx.is_lang_item(trait_ref.def_id, LangItem::AsyncFn)
159 && tcx.is_lang_item(def_id, LangItem::CallRefFuture))
160 {
161 diag.help("you may have forgotten to await an async function");
166 diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("it is currently not possible to add bounds constraining the future returned from an async function (`{0}`)",
item_name))
})format!("it is currently not possible to add bounds constraining the future returned from an async function (`{item_name}`)"));
167 note = false;
170 } else {
171 let mut matching_span = None;
177 let mut matched_end_of_args = false;
178 for bound in generics.bounds_for_param(local_id) {
179 let potential_spans = bound.bounds.iter().find_map(|bound| {
180 let bound_trait_path = bound.trait_ref()?.path;
181 let def_id = bound_trait_path.res.opt_def_id()?;
182 let generic_args = bound_trait_path
183 .segments
184 .iter()
185 .last()
186 .map(|path| path.args());
187 (def_id == trait_ref.def_id)
188 .then_some((bound_trait_path.span, generic_args))
189 });
190
191 if let Some((end_of_trait, end_of_args)) = potential_spans {
192 let args_span = end_of_args.and_then(|args| args.span());
193 matched_end_of_args = args_span.is_some();
194 matching_span = args_span
195 .or_else(|| Some(end_of_trait))
196 .map(|span| span.shrink_to_hi());
197 break;
198 }
199 }
200
201 if matched_end_of_args {
202 let path = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0}{1} = {2}", item_name,
item_args, p))
})format!(", {item_name}{item_args} = {p}");
204 note = !suggest_constraining_type_param(
205 tcx,
206 generics,
207 diag,
208 &proj.self_ty().to_string(),
209 &path,
210 None,
211 matching_span,
212 );
213 } else {
214 let path = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}{1} = {2}>", item_name,
item_args, p))
})format!("<{item_name}{item_args} = {p}>");
218 note = !suggest_constraining_type_param(
219 tcx,
220 generics,
221 diag,
222 &proj.self_ty().to_string(),
223 &path,
224 None,
225 matching_span,
226 );
227 }
228 }
229 }
230 if note {
231 diag.note("you might be missing a type parameter or trait bound");
232 }
233 }
234 (
235 ty::Param(p),
236 ty::Dynamic(..) | ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }),
237 )
238 | (
239 ty::Dynamic(..) | ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }),
240 ty::Param(p),
241 ) => {
242 if let Some(generics) = body_generics {
243 let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
244 let expected = match (values.expected.kind(), values.found.kind()) {
245 (ty::Param(_), _) => "expected ",
246 (_, ty::Param(_)) => "found ",
247 _ => "",
248 };
249 if !sp.contains(p_span) {
250 diag.span_label(p_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}this type parameter", expected))
})format!("{expected}this type parameter"));
251 }
252 }
253 diag.help("type parameters must be constrained to match other types");
254 if diag.code.is_some_and(|code| tcx.sess.teach(code)) {
255 diag.help(
256 "given a type parameter `T` and a method `foo`:
257```
258trait Trait<T> { fn foo(&self) -> T; }
259```
260the only ways to implement method `foo` are:
261- constrain `T` with an explicit type:
262```
263impl Trait<String> for X {
264 fn foo(&self) -> String { String::new() }
265}
266```
267- add a trait bound to `T` and call a method on that trait that returns `Self`:
268```
269impl<T: std::default::Default> Trait<T> for X {
270 fn foo(&self) -> T { <T as std::default::Default>::default() }
271}
272```
273- change `foo` to return an argument of type `T`:
274```
275impl<T> Trait<T> for X {
276 fn foo(&self, x: T) -> T { x }
277}
278```",
279 );
280 }
281 diag.note(
282 "for more information, visit \
283 https://doc.rust-lang.org/book/ch10-02-traits.html\
284 #traits-as-parameters",
285 );
286 }
287 (
288 ty::Param(p),
289 ty::Closure(..) | ty::CoroutineClosure(..) | ty::Coroutine(..),
290 ) => {
291 if let Some(generics) = body_generics {
292 let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
293 if !sp.contains(p_span) {
294 diag.span_label(p_span, "expected this type parameter");
295 }
296 }
297 diag.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("every closure has a distinct type and so could not always match the caller-chosen type of parameter `{0}`",
p))
})format!(
298 "every closure has a distinct type and so could not always match the \
299 caller-chosen type of parameter `{p}`"
300 ));
301 }
302 (ty::Param(p), _) | (_, ty::Param(p)) if let Some(generics) = body_generics => {
303 let p_span = tcx.def_span(generics.type_param(p, tcx).def_id);
304 let expected = match (values.expected.kind(), values.found.kind()) {
305 (ty::Param(_), _) => "expected ",
306 (_, ty::Param(_)) => "found ",
307 _ => "",
308 };
309 if !sp.contains(p_span) {
310 diag.span_label(p_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}this type parameter", expected))
})format!("{expected}this type parameter"));
311 }
312 }
313 (
314 ty::Alias(
315 _,
316 proj_ty @ ty::AliasTy {
317 kind: ty::Projection { def_id } | ty::Inherent { def_id },
318 ..
319 },
320 ),
321 _,
322 ) if !tcx.is_impl_trait_in_trait(def_id) => {
323 self.expected_projection(
324 diag,
325 proj_ty,
326 values,
327 body_owner_def_id,
328 cause.code(),
329 );
330 }
331 (
334 _,
335 ty::Alias(
336 _,
337 proj_ty @ ty::AliasTy {
338 kind: ty::Projection { def_id } | ty::Inherent { def_id },
339 ..
340 },
341 ),
342 ) if !tcx.is_impl_trait_in_trait(def_id)
343 && !tcx
344 .erase_and_anonymize_regions(values.expected)
345 .contains(tcx.erase_and_anonymize_regions(values.found)) =>
346 {
347 let msg = || {
348 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider constraining the associated type `{0}` to `{1}`",
values.found, values.expected))
})format!(
349 "consider constraining the associated type `{}` to `{}`",
350 values.found, values.expected,
351 )
352 };
353 let suggested_projection_constraint =
354 #[allow(non_exhaustive_omitted_patterns)] match proj_ty.kind {
ty::Projection { .. } => true,
_ => false,
}matches!(proj_ty.kind, ty::Projection { .. })
355 && (self.suggest_constraining_opaque_associated_type(
356 diag,
357 msg,
358 proj_ty,
359 values.expected,
360 ) || self.suggest_constraint(
361 diag,
362 &msg,
363 body_owner_def_id,
364 proj_ty,
365 values.expected,
366 ));
367 if !suggested_projection_constraint {
368 diag.help(msg());
369 diag.note(
370 "for more information, visit \
371 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
372 );
373 }
374 }
375 (
376 ty::Dynamic(t, _),
377 ty::Alias(
378 _,
379 ty::AliasTy { kind: ty::Opaque { def_id: opaque_def_id }, .. },
380 ),
381 ) if let Some(def_id) = t.principal_def_id()
382 && tcx
383 .explicit_item_self_bounds(opaque_def_id)
384 .skip_binder()
385 .iter()
386 .any(|(pred, _span)| match pred.kind().skip_binder() {
387 ty::ClauseKind::Trait(trait_predicate)
388 if trait_predicate.polarity
389 == ty::PredicatePolarity::Positive =>
390 {
391 trait_predicate.def_id() == def_id
392 }
393 _ => false,
394 }) =>
395 {
396 diag.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("you can box the `{0}` to coerce it to `Box<{1}>`, but you\'ll have to change the expected type as well",
values.found, values.expected))
})format!(
397 "you can box the `{}` to coerce it to `Box<{}>`, but you'll have to \
398 change the expected type as well",
399 values.found, values.expected,
400 ));
401 }
402 (ty::Dynamic(t, _), _) if let Some(def_id) = t.principal_def_id() => {
403 let mut has_matching_impl = false;
404 tcx.for_each_relevant_impl(def_id, values.found, |did| {
405 if DeepRejectCtxt::relate_rigid_infer(tcx)
406 .types_may_unify(values.found, tcx.type_of(did).skip_binder())
407 {
408 has_matching_impl = true;
409 }
410 });
411 if has_matching_impl {
412 let trait_name = tcx.item_name(def_id);
413 diag.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements `{1}` so you could box the found value and coerce it to the trait object `Box<dyn {1}>`, you will have to change the expected type as well",
values.found, trait_name))
})format!(
414 "`{}` implements `{trait_name}` so you could box the found value \
415 and coerce it to the trait object `Box<dyn {trait_name}>`, you \
416 will have to change the expected type as well",
417 values.found,
418 ));
419 }
420 }
421 (_, ty::Dynamic(t, _)) if let Some(def_id) = t.principal_def_id() => {
422 let mut has_matching_impl = false;
423 tcx.for_each_relevant_impl(def_id, values.expected, |did| {
424 if DeepRejectCtxt::relate_rigid_infer(tcx)
425 .types_may_unify(values.expected, tcx.type_of(did).skip_binder())
426 {
427 has_matching_impl = true;
428 }
429 });
430 if has_matching_impl {
431 let trait_name = tcx.item_name(def_id);
432 diag.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements `{1}` so you could change the expected type to `Box<dyn {1}>`",
values.expected, trait_name))
})format!(
433 "`{}` implements `{trait_name}` so you could change the expected \
434 type to `Box<dyn {trait_name}>`",
435 values.expected,
436 ));
437 }
438 }
439 (_, ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }))
440 | (ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }), _) => {
441 if let Some(body_owner_def_id) = body_owner_def_id
442 && def_id.is_local()
443 && #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(body_owner_def_id)
{
DefKind::Fn | DefKind::Static { .. } | DefKind::Const { .. } |
DefKind::AssocFn | DefKind::AssocConst { .. } => true,
_ => false,
}matches!(
444 tcx.def_kind(body_owner_def_id),
445 DefKind::Fn
446 | DefKind::Static { .. }
447 | DefKind::Const { .. }
448 | DefKind::AssocFn
449 | DefKind::AssocConst { .. }
450 )
451 && #[allow(non_exhaustive_omitted_patterns)] match tcx.opaque_ty_origin(def_id) {
hir::OpaqueTyOrigin::TyAlias { .. } => true,
_ => false,
}matches!(
452 tcx.opaque_ty_origin(def_id),
453 hir::OpaqueTyOrigin::TyAlias { .. }
454 )
455 && !tcx
456 .opaque_types_defined_by(body_owner_def_id.expect_local())
457 .contains(&def_id.expect_local())
458 {
459 let sp = tcx
460 .def_ident_span(body_owner_def_id)
461 .unwrap_or_else(|| tcx.def_span(body_owner_def_id));
462 let mut alias_def_id = def_id;
463 while let DefKind::OpaqueTy = tcx.def_kind(alias_def_id) {
464 alias_def_id = tcx.parent(alias_def_id);
465 }
466 let opaque_path = tcx.def_path_str(alias_def_id);
467 match tcx.opaque_ty_origin(def_id) {
469 rustc_hir::OpaqueTyOrigin::FnReturn { .. } => {}
470 rustc_hir::OpaqueTyOrigin::AsyncFn { .. } => {}
471 rustc_hir::OpaqueTyOrigin::TyAlias {
472 in_assoc_ty: false, ..
473 } => {
474 diag.span_note(
475 sp,
476 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this item must have a `#[define_opaque({0})]` attribute to be able to define hidden types",
opaque_path))
})format!("this item must have a `#[define_opaque({opaque_path})]` \
477 attribute to be able to define hidden types"),
478 );
479 }
480 rustc_hir::OpaqueTyOrigin::TyAlias {
481 in_assoc_ty: true, ..
482 } => {}
483 }
484 }
485 let ObligationCauseCode::IfExpression { expr_id, .. } = cause.code() else {
488 return;
489 };
490 let hir::Node::Expr(&hir::Expr {
491 kind:
492 hir::ExprKind::If(
493 _,
494 &hir::Expr {
495 kind:
496 hir::ExprKind::Block(
497 &hir::Block { expr: Some(then), .. },
498 _,
499 ),
500 ..
501 },
502 Some(&hir::Expr {
503 kind:
504 hir::ExprKind::Block(
505 &hir::Block { expr: Some(else_), .. },
506 _,
507 ),
508 ..
509 }),
510 ),
511 ..
512 }) = self.tcx.hir_node(*expr_id)
513 else {
514 return;
515 };
516 let expected = match values.found.kind() {
517 ty::Alias(..) => values.expected,
518 _ => values.found,
519 };
520 let preds = tcx.explicit_item_self_bounds(def_id);
521 for (pred, _span) in preds.skip_binder() {
522 let ty::ClauseKind::Trait(trait_predicate) = pred.kind().skip_binder()
523 else {
524 continue;
525 };
526 if trait_predicate.polarity != ty::PredicatePolarity::Positive {
527 continue;
528 }
529 let def_id = trait_predicate.def_id();
530 let mut impl_def_ids = ::alloc::vec::Vec::new()vec![];
531 tcx.for_each_relevant_impl(def_id, expected, |did| {
532 impl_def_ids.push(did)
533 });
534 if let [_] = &impl_def_ids[..] {
535 let trait_name = tcx.item_name(def_id);
536 diag.multipart_suggestion(
537 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements `{1}` so you can box both arms and coerce to the trait object `Box<dyn {1}>`",
expected, trait_name))
})format!(
538 "`{expected}` implements `{trait_name}` so you can box \
539 both arms and coerce to the trait object \
540 `Box<dyn {trait_name}>`",
541 ),
542 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(then.span.shrink_to_lo(), "Box::new(".to_string()),
(then.span.shrink_to_hi(),
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(") as Box<dyn {0}>",
tcx.def_path_str(def_id)))
})), (else_.span.shrink_to_lo(), "Box::new(".to_string()),
(else_.span.shrink_to_hi(), ")".to_string())]))vec![
543 (then.span.shrink_to_lo(), "Box::new(".to_string()),
544 (
545 then.span.shrink_to_hi(),
546 format!(") as Box<dyn {}>", tcx.def_path_str(def_id)),
547 ),
548 (else_.span.shrink_to_lo(), "Box::new(".to_string()),
549 (else_.span.shrink_to_hi(), ")".to_string()),
550 ],
551 MachineApplicable,
552 );
553 }
554 }
555 }
556 (ty::FnPtr(_, hdr), ty::FnDef(def_id, _))
557 | (ty::FnDef(def_id, _), ty::FnPtr(_, hdr)) => {
558 if tcx.fn_sig(def_id).skip_binder().safety() < hdr.safety() {
559 if !tcx.codegen_fn_attrs(def_id).safe_target_features {
560 diag.note(
561 "unsafe functions cannot be coerced into safe function pointers",
562 );
563 }
564 }
565 }
566 (ty::Adt(_, _), ty::Adt(def, args))
567 if let ObligationCauseCode::IfExpression { expr_id, .. } = cause.code()
568 && let hir::Node::Expr(if_expr) = self.tcx.hir_node(*expr_id)
569 && let hir::ExprKind::If(_, then_expr, _) = if_expr.kind
570 && let hir::ExprKind::Block(blk, _) = then_expr.kind
571 && let Some(then) = blk.expr
572 && def.is_box()
573 && let boxed_ty = args.type_at(0)
574 && let ty::Dynamic(t, _) = boxed_ty.kind()
575 && let Some(def_id) = t.principal_def_id()
576 && let mut impl_def_ids = ::alloc::vec::Vec::new()vec![]
577 && let _ =
578 tcx.for_each_relevant_impl(def_id, values.expected, |did| {
579 impl_def_ids.push(did)
580 })
581 && let [_] = &impl_def_ids[..] =>
582 {
583 diag.multipart_suggestion(
586 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements `{1}` so you can box it to coerce to the trait object `{2}`",
values.expected, tcx.item_name(def_id), values.found))
})format!(
587 "`{}` implements `{}` so you can box it to coerce to the trait \
588 object `{}`",
589 values.expected,
590 tcx.item_name(def_id),
591 values.found,
592 ),
593 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(then.span.shrink_to_lo(), "Box::new(".to_string()),
(then.span.shrink_to_hi(), ")".to_string())]))vec![
594 (then.span.shrink_to_lo(), "Box::new(".to_string()),
595 (then.span.shrink_to_hi(), ")".to_string()),
596 ],
597 MachineApplicable,
598 );
599 }
600 _ => {}
601 }
602 {
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/infer/note_and_explain.rs:602",
"rustc_trait_selection::error_reporting::infer::note_and_explain",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs"),
::tracing_core::__macro_support::Option::Some(602u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::note_and_explain"),
::tracing_core::field::FieldSet::new(&["message"],
::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};
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!("note_and_explain_type_err expected={0:?} ({1:?}) found={2:?} ({3:?})",
values.expected, values.expected.kind(), values.found,
values.found.kind()) as &dyn Value))])
});
} else { ; }
};debug!(
603 "note_and_explain_type_err expected={:?} ({:?}) found={:?} ({:?})",
604 values.expected,
605 values.expected.kind(),
606 values.found,
607 values.found.kind(),
608 );
609 }
610 TypeError::CyclicTy(ty) => {
611 if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() {
613 diag.note(
614 "closures cannot capture themselves or take themselves as argument;\n\
615 this error may be the result of a recent compiler bug-fix,\n\
616 see issue #46062 <https://github.com/rust-lang/rust/issues/46062>\n\
617 for more information",
618 );
619 }
620 }
621 TypeError::TargetFeatureCast(def_id) => {
622 let target_spans = {
{
'done:
{
for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(TargetFeature {
attr_span: span, was_forced: false, .. }) => {
break 'done Some(*span);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, def_id, TargetFeature{attr_span: span, was_forced: false, ..} => *span);
623 diag.note(
624 "functions with `#[target_feature]` can only be coerced to `unsafe` function pointers"
625 );
626 diag.span_labels(target_spans, "`#[target_feature]` added here");
627 }
628 _ => {}
629 }
630 }
631
632 fn suggest_constraint(
633 &self,
634 diag: &mut Diag<'_>,
635 msg: impl Fn() -> String,
636 body_owner_def_id: Option<DefId>,
637 alias_ty: ty::AliasTy<'tcx>,
638 ty: Ty<'tcx>,
639 ) -> bool {
640 let tcx = self.tcx;
641 let Some(proj_ty) = alias_ty.try_to_projection() else {
643 return false;
644 };
645 let Some(body_owner_def_id) = body_owner_def_id else {
646 return false;
647 };
648 let assoc = tcx.associated_item(proj_ty.kind);
649 let (trait_ref, assoc_args) = alias_ty.trait_ref_and_own_args(tcx);
650 let Some(item) = tcx.hir_get_if_local(body_owner_def_id) else {
651 return false;
652 };
653 let Some(hir_generics) = item.generics() else {
654 return false;
655 };
656 let ty::Param(param_ty) = *alias_ty.self_ty().kind() else {
659 return false;
660 };
661 let generics = tcx.generics_of(body_owner_def_id);
662 let def_id = generics.type_param(param_ty, tcx).def_id;
663 let Some(def_id) = def_id.as_local() else {
664 return false;
665 };
666
667 for pred in hir_generics.bounds_for_param(def_id) {
670 if self.constrain_generic_bound_associated_type_structured_suggestion(
671 diag,
672 trait_ref,
673 pred.bounds,
674 assoc,
675 assoc_args,
676 ty,
677 &msg,
678 false,
679 ) {
680 return true;
681 }
682 }
683 if (param_ty.index as usize) >= generics.parent_count {
684 return false;
686 }
687 let hir_id = match item {
689 hir::Node::ImplItem(item) => item.hir_id(),
690 hir::Node::TraitItem(item) => item.hir_id(),
691 _ => return false,
692 };
693 let parent = tcx.hir_get_parent_item(hir_id).def_id;
694 self.suggest_constraint(diag, msg, Some(parent.into()), alias_ty, ty)
695 }
696
697 fn expected_projection(
711 &self,
712 diag: &mut Diag<'_>,
713 proj_ty: ty::AliasTy<'tcx>,
714 values: ExpectedFound<Ty<'tcx>>,
715 body_owner_def_id: Option<DefId>,
716 cause_code: &ObligationCauseCode<'_>,
717 ) {
718 let tcx = self.tcx;
719
720 if self
722 .tcx
723 .erase_and_anonymize_regions(values.found)
724 .contains(self.tcx.erase_and_anonymize_regions(values.expected))
725 {
726 return;
727 }
728
729 let (ty::Projection { def_id } | ty::Inherent { def_id }) = proj_ty.kind else {
730 {
::core::panicking::panic_fmt(format_args!("expected projection or inherent alias, found {0:?}",
proj_ty.kind));
};panic!("expected projection or inherent alias, found {:?}", proj_ty.kind);
731 };
732
733 let msg = || {
734 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider constraining the associated type `{0}` to `{1}`",
values.expected, values.found))
})format!(
735 "consider constraining the associated type `{}` to `{}`",
736 values.expected, values.found
737 )
738 };
739
740 let body_owner = body_owner_def_id.and_then(|id| tcx.hir_get_if_local(id));
741 let current_method_ident = body_owner.and_then(|n| n.ident()).map(|i| i.name);
742
743 let callable_scope = #[allow(non_exhaustive_omitted_patterns)] match body_owner {
Some(hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { .. }, .. }) |
hir::Node::TraitItem(hir::TraitItem {
kind: hir::TraitItemKind::Fn(..), .. }) |
hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..),
.. })) => true,
_ => false,
}matches!(
745 body_owner,
746 Some(
747 hir::Node::Item(hir::Item { kind: hir::ItemKind::Fn { .. }, .. })
748 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Fn(..), .. })
749 | hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), .. }),
750 )
751 );
752 let impl_comparison = #[allow(non_exhaustive_omitted_patterns)] match cause_code {
ObligationCauseCode::CompareImplItem { .. } => true,
_ => false,
}matches!(cause_code, ObligationCauseCode::CompareImplItem { .. });
753 if impl_comparison {
754 } else {
757 let point_at_assoc_fn = if callable_scope
758 && self.point_at_methods_that_satisfy_associated_type(
759 diag,
760 tcx.parent(def_id),
761 current_method_ident,
762 def_id,
763 values.expected,
764 ) {
765 true
770 } else {
771 false
772 };
773 if self.suggest_constraint(diag, &msg, body_owner_def_id, proj_ty, values.found)
776 || point_at_assoc_fn
777 {
778 return;
779 }
780 }
781
782 self.suggest_constraining_opaque_associated_type(diag, &msg, proj_ty, values.found);
783
784 if self.point_at_associated_type(diag, body_owner_def_id, values.found) {
785 return;
786 }
787
788 if !impl_comparison {
789 if callable_scope {
791 diag.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} or calling a method that returns `{1}`",
msg(), values.expected))
})format!(
792 "{} or calling a method that returns `{}`",
793 msg(),
794 values.expected
795 ));
796 } else {
797 diag.help(msg());
798 }
799 diag.note(
800 "for more information, visit \
801 https://doc.rust-lang.org/book/ch19-03-advanced-traits.html",
802 );
803 }
804 if diag.code.is_some_and(|code| tcx.sess.teach(code)) {
805 diag.help(
806 "given an associated type `T` and a method `foo`:
807```
808trait Trait {
809type T;
810fn foo(&self) -> Self::T;
811}
812```
813the only way of implementing method `foo` is to constrain `T` with an explicit associated type:
814```
815impl Trait for X {
816type T = String;
817fn foo(&self) -> Self::T { String::new() }
818}
819```",
820 );
821 }
822 }
823
824 fn suggest_constraining_opaque_associated_type(
827 &self,
828 diag: &mut Diag<'_>,
829 msg: impl Fn() -> String,
830 proj_ty: ty::AliasTy<'tcx>,
831 ty: Ty<'tcx>,
832 ) -> bool {
833 let tcx = self.tcx;
834
835 let (ty::Projection { def_id } | ty::Inherent { def_id }) = proj_ty.kind else {
836 {
::core::panicking::panic_fmt(format_args!("expected projection or inherent alias, found {0:?}",
proj_ty.kind));
};panic!("expected projection or inherent alias, found {:?}", proj_ty.kind);
837 };
838
839 let assoc = tcx.associated_item(def_id);
840 if let ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) =
841 *proj_ty.self_ty().kind()
842 {
843 let opaque_local_def_id = def_id.as_local();
844 let opaque_hir_ty = if let Some(opaque_local_def_id) = opaque_local_def_id {
845 tcx.hir_expect_opaque_ty(opaque_local_def_id)
846 } else {
847 return false;
848 };
849
850 let (trait_ref, assoc_args) = proj_ty.trait_ref_and_own_args(tcx);
851
852 self.constrain_generic_bound_associated_type_structured_suggestion(
853 diag,
854 trait_ref,
855 opaque_hir_ty.bounds,
856 assoc,
857 assoc_args,
858 ty,
859 msg,
860 true,
861 )
862 } else {
863 false
864 }
865 }
866
867 fn point_at_methods_that_satisfy_associated_type(
868 &self,
869 diag: &mut Diag<'_>,
870 assoc_container_id: DefId,
871 current_method_ident: Option<Symbol>,
872 proj_ty_item_def_id: DefId,
873 expected: Ty<'tcx>,
874 ) -> bool {
875 let tcx = self.tcx;
876
877 let items = tcx.associated_items(assoc_container_id);
878 let methods: Vec<(Span, String)> = items
882 .in_definition_order()
883 .filter(|item| {
884 item.is_fn()
885 && Some(item.name()) != current_method_ident
886 && !tcx.is_doc_hidden(item.def_id)
887 })
888 .filter_map(|item| {
889 let method = tcx.fn_sig(item.def_id).instantiate_identity().skip_norm_wip();
890 match *method.output().skip_binder().kind() {
891 ty::Alias(
892 _,
893 ty::AliasTy { kind: ty::Projection { def_id: item_def_id }, .. },
894 ) if item_def_id == proj_ty_item_def_id => Some((
895 tcx.def_span(item.def_id),
896 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider calling `{0}`",
tcx.def_path_str(item.def_id)))
})format!("consider calling `{}`", tcx.def_path_str(item.def_id)),
897 )),
898 _ => None,
899 }
900 })
901 .collect();
902 if !methods.is_empty() {
903 let mut span: MultiSpan =
906 methods.iter().map(|(sp, _)| *sp).collect::<Vec<Span>>().into();
907 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} method{1} {2} available that return{3} `{4}`",
if methods.len() == 1 { "a" } else { "some" },
if methods.len() == 1 { "" } else { "s" },
if methods.len() == 1 { "is" } else { "are" },
if methods.len() == 1 { "s" } else { "" }, expected))
})format!(
908 "{some} method{s} {are} available that return{r} `{ty}`",
909 some = if methods.len() == 1 { "a" } else { "some" },
910 s = pluralize!(methods.len()),
911 are = pluralize!("is", methods.len()),
912 r = if methods.len() == 1 { "s" } else { "" },
913 ty = expected
914 );
915 for (sp, label) in methods.into_iter() {
916 span.push_span_label(sp, label);
917 }
918 diag.span_help(span, msg);
919 return true;
920 }
921 false
922 }
923
924 fn point_at_associated_type(
925 &self,
926 diag: &mut Diag<'_>,
927 body_owner_def_id: Option<DefId>,
928 found: Ty<'tcx>,
929 ) -> bool {
930 let tcx = self.tcx;
931
932 let Some(def_id) = body_owner_def_id.and_then(|id| id.as_local()) else {
933 return false;
934 };
935
936 let hir_id = tcx.local_def_id_to_hir_id(def_id);
939 let parent_id = tcx.hir_get_parent_item(hir_id);
940 let item = tcx.hir_node_by_def_id(parent_id.def_id);
941
942 {
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/infer/note_and_explain.rs:942",
"rustc_trait_selection::error_reporting::infer::note_and_explain",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/note_and_explain.rs"),
::tracing_core::__macro_support::Option::Some(942u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer::note_and_explain"),
::tracing_core::field::FieldSet::new(&["message"],
::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};
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!("expected_projection parent item {0:?}",
item) as &dyn Value))])
});
} else { ; }
};debug!("expected_projection parent item {:?}", item);
943
944 let param_env = tcx.param_env(def_id);
945
946 if let DefKind::Trait | DefKind::Impl { .. } = tcx.def_kind(parent_id) {
947 let assoc_items = tcx.associated_items(parent_id);
948 for assoc_item in assoc_items.in_definition_order() {
950 if assoc_item.is_type()
951 && let hir::Defaultness::Default { has_value: true } = assoc_item.defaultness(tcx)
954 && let assoc_ty = tcx.type_of(assoc_item.def_id).instantiate_identity().skip_norm_wip()
955 && self.infcx.can_eq(param_env, assoc_ty, found)
956 {
957 let msg = match assoc_item.container {
958 ty::AssocContainer::Trait => {
959 "associated type defaults can't be assumed inside the \
960 trait defining them"
961 }
962 ty::AssocContainer::InherentImpl | ty::AssocContainer::TraitImpl(_) => {
963 "associated type is `default` and may be overridden"
964 }
965 };
966 diag.span_label(tcx.def_span(assoc_item.def_id), msg);
967 return true;
968 }
969 }
970 }
971
972 false
973 }
974
975 fn constrain_generic_bound_associated_type_structured_suggestion(
983 &self,
984 diag: &mut Diag<'_>,
985 trait_ref: ty::TraitRef<'tcx>,
986 bounds: hir::GenericBounds<'_>,
987 assoc: ty::AssocItem,
988 assoc_args: &[ty::GenericArg<'tcx>],
989 ty: Ty<'tcx>,
990 msg: impl Fn() -> String,
991 is_bound_surely_present: bool,
992 ) -> bool {
993 let trait_bounds = bounds.iter().filter_map(|bound| match bound {
996 hir::GenericBound::Trait(ptr) if ptr.modifiers == hir::TraitBoundModifiers::NONE => {
997 Some(ptr)
998 }
999 _ => None,
1000 });
1001
1002 let matching_trait_bounds = trait_bounds
1003 .clone()
1004 .filter(|ptr| ptr.trait_ref.trait_def_id() == Some(trait_ref.def_id))
1005 .collect::<Vec<_>>();
1006
1007 let span = match &matching_trait_bounds[..] {
1008 &[ptr] => ptr.span,
1009 &[] if is_bound_surely_present => match &trait_bounds.collect::<Vec<_>>()[..] {
1010 &[ptr] => ptr.span,
1011 _ => return false,
1012 },
1013 _ => return false,
1014 };
1015
1016 self.constrain_associated_type_structured_suggestion(diag, span, assoc, assoc_args, ty, msg)
1017 }
1018
1019 fn constrain_associated_type_structured_suggestion(
1022 &self,
1023 diag: &mut Diag<'_>,
1024 span: Span,
1025 assoc: ty::AssocItem,
1026 assoc_args: &[ty::GenericArg<'tcx>],
1027 ty: Ty<'tcx>,
1028 msg: impl Fn() -> String,
1029 ) -> bool {
1030 let tcx = self.tcx;
1031
1032 if let Ok(has_params) =
1033 tcx.sess.source_map().span_to_snippet(span).map(|snippet| snippet.ends_with('>'))
1034 {
1035 let (span, sugg) = if has_params {
1036 let pos = span.hi() - BytePos(1);
1037 let span = Span::new(pos, pos, span.ctxt(), span.parent());
1038 (span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(", {0} = {1}", assoc.ident(tcx),
ty))
})format!(", {} = {}", assoc.ident(tcx), ty))
1039 } else {
1040 let item_args = self.format_generic_args(assoc_args);
1041 (span.shrink_to_hi(), ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("<{0}{1} = {2}>", assoc.ident(tcx),
item_args, ty))
})format!("<{}{} = {}>", assoc.ident(tcx), item_args, ty))
1042 };
1043 diag.span_suggestion_verbose(span, msg(), sugg, MaybeIncorrect);
1044 return true;
1045 }
1046 false
1047 }
1048
1049 pub fn format_generic_args(&self, args: &[ty::GenericArg<'tcx>]) -> String {
1050 FmtPrinter::print_string(self.tcx, hir::def::Namespace::TypeNS, |p| {
1051 p.print_path_with_generic_args(|_| Ok(()), args)
1052 })
1053 .expect("could not write to `String`.")
1054 }
1055}