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