1use core::ops::ControlFlow;
3use std::borrow::Cow;
4use std::collections::hash_set;
5use std::path::PathBuf;
6
7use rustc_ast::ast::LitKind;
8use rustc_ast::{LitIntType, TraitObjectSyntax};
9use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10use rustc_data_structures::unord::UnordSet;
11use rustc_errors::codes::*;
12use rustc_errors::{
13 Applicability, Diag, ErrorGuaranteed, Level, MultiSpan, StashKey, StringPart, Suggestions, msg,
14 pluralize, struct_span_code_err,
15};
16use rustc_hir::attrs::diagnostic::CustomDiagnostic;
17use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
18use rustc_hir::intravisit::Visitor;
19use rustc_hir::{self as hir, LangItem, Node, find_attr};
20use rustc_infer::infer::{InferOk, TypeTrace};
21use rustc_infer::traits::ImplSource;
22use rustc_infer::traits::solve::Goal;
23use rustc_middle::traits::SignatureMismatchData;
24use rustc_middle::traits::select::OverflowError;
25use rustc_middle::ty::abstract_const::NotConstEvaluatable;
26use rustc_middle::ty::error::{ExpectedFound, TypeError};
27use rustc_middle::ty::print::{
28 PrintPolyTraitPredicateExt, PrintPolyTraitRefExt as _, PrintTraitPredicateExt as _,
29 PrintTraitRefExt as _, with_forced_trimmed_paths,
30};
31use rustc_middle::ty::{
32 self, GenericArgKind, TraitRef, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
33 TypeVisitableExt, Unnormalized, Upcast,
34};
35use rustc_middle::{bug, span_bug};
36use rustc_span::def_id::CrateNum;
37use rustc_span::{BytePos, DUMMY_SP, STDLIB_STABLE_CRATES, Span, Symbol, sym};
38use tracing::{debug, instrument};
39
40use super::suggestions::get_explanation_based_on_obligation;
41use super::{ArgKind, CandidateSimilarity, GetSafeTransmuteErrorAndReason, ImplCandidate};
42use crate::diagnostics::{
43 ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch, CoroClosureNotFn,
44};
45use crate::error_reporting::TypeErrCtxt;
46use crate::error_reporting::infer::TyCategory;
47use crate::error_reporting::traits::report_dyn_incompatibility;
48use crate::infer::{self, InferCtxt, InferCtxtExt as _};
49use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
50use crate::traits::{
51 MismatchedProjectionTypes, NormalizeExt, Obligation, ObligationCause, ObligationCauseCode,
52 ObligationCtxt, PredicateObligation, SelectionContext, SelectionError, elaborate,
53 specialization_graph,
54};
55
56impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
57 pub fn report_selection_error(
61 &self,
62 mut obligation: PredicateObligation<'tcx>,
63 root_obligation: &PredicateObligation<'tcx>,
64 error: &SelectionError<'tcx>,
65 ) -> ErrorGuaranteed {
66 let tcx = self.tcx;
67 let mut span = obligation.cause.span;
68 let mut long_ty_file = None;
69
70 let mut err = match *error {
71 SelectionError::Unimplemented => {
72 if let ObligationCauseCode::WellFormed(Some(wf_loc)) =
75 root_obligation.cause.code().peel_derives()
76 && !obligation.predicate.has_non_region_infer()
77 {
78 if let Some(cause) = self.tcx.diagnostic_hir_wf_check((
79 tcx.erase_and_anonymize_regions(obligation.predicate),
80 *wf_loc,
81 )) {
82 obligation.cause = cause.clone();
83 span = obligation.cause.span;
84 }
85 }
86
87 if let ObligationCauseCode::CompareImplItem {
88 impl_item_def_id,
89 trait_item_def_id,
90 kind: _,
91 } = *obligation.cause.code()
92 {
93 {
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/fulfillment_errors.rs:93",
"rustc_trait_selection::error_reporting::traits::fulfillment_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
::tracing_core::__macro_support::Option::Some(93u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::fulfillment_errors"),
::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!("ObligationCauseCode::CompareImplItemObligation")
as &dyn Value))])
});
} else { ; }
};debug!("ObligationCauseCode::CompareImplItemObligation");
94 return self
95 .report_extra_impl_obligation(
96 span,
97 impl_item_def_id,
98 trait_item_def_id,
99 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", obligation.predicate))
})format!("`{}`", obligation.predicate),
100 )
101 .emit();
102 }
103
104 if let ObligationCauseCode::ConstParam(ty) = *obligation.cause.code().peel_derives()
106 {
107 return self.report_const_param_not_wf(ty, &obligation).emit();
108 }
109
110 let bound_predicate = obligation.predicate.kind();
111 match bound_predicate.skip_binder() {
112 ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_predicate)) => {
113 let leaf_trait_predicate =
114 self.resolve_vars_if_possible(bound_predicate.rebind(trait_predicate));
115
116 let (main_trait_predicate, main_obligation) =
123 if let ty::PredicateKind::Clause(
124 ty::ClauseKind::Trait(root_pred)
125 ) = root_obligation.predicate.kind().skip_binder()
126 && !leaf_trait_predicate.self_ty().skip_binder().has_escaping_bound_vars()
127 && !root_pred.self_ty().has_escaping_bound_vars()
128 && (
133 self.can_eq(
135 obligation.param_env,
136 leaf_trait_predicate.self_ty().skip_binder(),
137 root_pred.self_ty().peel_refs(),
138 )
139 || self.can_eq(
141 obligation.param_env,
142 leaf_trait_predicate.self_ty().skip_binder(),
143 root_pred.self_ty(),
144 )
145 )
146 && leaf_trait_predicate.def_id() != root_pred.def_id()
150 && !self.tcx.is_lang_item(root_pred.def_id(), LangItem::Unsize)
153 {
154 (
155 self.resolve_vars_if_possible(
156 root_obligation.predicate.kind().rebind(root_pred),
157 ),
158 root_obligation,
159 )
160 } else {
161 (leaf_trait_predicate, &obligation)
162 };
163
164 if let Some(guar) = self
165 .emit_specialized_closure_kind_error(&obligation, leaf_trait_predicate)
166 {
167 return guar;
168 }
169
170 if let Err(guar) = leaf_trait_predicate.error_reported() {
171 return guar;
172 }
173 if let Err(guar) = self.fn_arg_obligation(&obligation) {
176 return guar;
177 }
178 let (post_message, pre_message, type_def) = self
179 .get_parent_trait_ref(obligation.cause.code())
180 .map(|(t, s)| {
181 let t = self.tcx.short_string(t, &mut long_ty_file);
182 (
183 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" in `{0}`", t))
})format!(" in `{t}`"),
184 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("within `{0}`, ", t))
})format!("within `{t}`, "),
185 s.map(|s| (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("within this `{0}`", t))
})format!("within this `{t}`"), s)),
186 )
187 })
188 .unwrap_or_default();
189
190 let CustomDiagnostic { message, label, notes, parent_label } = self
191 .on_unimplemented_note(
192 main_trait_predicate,
193 main_obligation,
194 &mut long_ty_file,
195 );
196
197 let have_alt_message = message.is_some() || label.is_some();
198
199 let message = message.unwrap_or_else(|| {
200 self.get_standard_error_message(
201 main_trait_predicate,
202 None,
203 post_message,
204 &mut long_ty_file,
205 )
206 });
207 let is_try_conversion =
208 self.is_try_conversion(span, main_trait_predicate.def_id());
209 let is_question_mark = #[allow(non_exhaustive_omitted_patterns)] match root_obligation.cause.code().peel_derives()
{
ObligationCauseCode::QuestionMark => true,
_ => false,
}matches!(
210 root_obligation.cause.code().peel_derives(),
211 ObligationCauseCode::QuestionMark,
212 ) && !(self
213 .tcx
214 .is_diagnostic_item(sym::FromResidual, main_trait_predicate.def_id())
215 || self.tcx.is_lang_item(main_trait_predicate.def_id(), LangItem::Try));
216 let is_unsize =
217 self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Unsize);
218 let question_mark_message = "the question mark operation (`?`) implicitly \
219 performs a conversion on the error value \
220 using the `From` trait";
221 let (message, notes) = if is_try_conversion {
222 let ty = self.tcx.short_string(
223 main_trait_predicate.skip_binder().self_ty(),
224 &mut long_ty_file,
225 );
226 (
228 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`?` couldn\'t convert the error to `{0}`",
ty))
})format!("`?` couldn't convert the error to `{ty}`"),
229 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[question_mark_message.to_owned()]))vec![question_mark_message.to_owned()],
230 )
231 } else if is_question_mark {
232 let main_trait_predicate =
233 self.tcx.short_string(main_trait_predicate, &mut long_ty_file);
234 (
238 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`?` couldn\'t convert the error: `{0}` is not satisfied",
main_trait_predicate))
})format!(
239 "`?` couldn't convert the error: `{main_trait_predicate}` is \
240 not satisfied",
241 ),
242 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[question_mark_message.to_owned()]))vec![question_mark_message.to_owned()],
243 )
244 } else {
245 (message, notes)
246 };
247
248 let (err_msg, safe_transmute_explanation) = if self
249 .tcx
250 .is_lang_item(main_trait_predicate.def_id(), LangItem::TransmuteTrait)
251 {
252 let (report_obligation, report_pred) = self
254 .select_transmute_obligation_for_reporting(
255 &obligation,
256 main_trait_predicate,
257 root_obligation,
258 );
259
260 match self.get_safe_transmute_error_and_reason(
261 report_obligation,
262 report_pred,
263 span,
264 ) {
265 GetSafeTransmuteErrorAndReason::Silent => {
266 return self
267 .dcx()
268 .span_delayed_bug(span, "silent safe transmute error");
269 }
270 GetSafeTransmuteErrorAndReason::Default => (message, None),
271 GetSafeTransmuteErrorAndReason::Error {
272 err_msg,
273 safe_transmute_explanation,
274 } => (err_msg, safe_transmute_explanation),
275 }
276 } else {
277 (message, None)
278 };
279
280 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", err_msg))
})).with_code(E0277)
}struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg);
281
282 let trait_def_id = main_trait_predicate.def_id();
283 let leaf_trait_def_id = leaf_trait_predicate.def_id();
284 if (self.tcx.is_diagnostic_item(sym::From, trait_def_id)
285 || self.tcx.is_diagnostic_item(sym::TryFrom, trait_def_id))
286 && (self.tcx.is_diagnostic_item(sym::From, leaf_trait_def_id)
287 || self.tcx.is_diagnostic_item(sym::TryFrom, leaf_trait_def_id))
288 {
289 let trait_ref = leaf_trait_predicate.skip_binder().trait_ref;
290
291 if let Some(found_ty) =
292 trait_ref.args.get(1).and_then(|arg| arg.as_type())
293 {
294 let ty = main_trait_predicate.skip_binder().self_ty();
295
296 if let Some(cast_ty) =
297 self.find_explicit_cast_type(obligation.param_env, found_ty, ty)
298 {
299 let found_ty_str =
300 self.tcx.short_string(found_ty, &mut long_ty_file);
301 let cast_ty_str =
302 self.tcx.short_string(cast_ty, &mut long_ty_file);
303
304 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider casting the `{0}` value to `{1}`",
found_ty_str, cast_ty_str))
})format!(
305 "consider casting the `{found_ty_str}` value to `{cast_ty_str}`",
306 ));
307 }
308 }
309 }
310
311 *err.long_ty_path() = long_ty_file;
312
313 let mut suggested = false;
314 let mut noted_missing_impl = false;
315 if is_try_conversion || is_question_mark {
316 (suggested, noted_missing_impl) = self.try_conversion_context(
317 &obligation,
318 main_trait_predicate,
319 &mut err,
320 );
321 }
322
323 suggested |= self.detect_negative_literal(
324 &obligation,
325 main_trait_predicate,
326 &mut err,
327 );
328
329 if let Some(ret_span) = self.return_type_span(&obligation) {
330 if is_try_conversion {
331 let ty = self.tcx.short_string(
332 main_trait_predicate.skip_binder().self_ty(),
333 err.long_ty_path(),
334 );
335 err.span_label(
336 ret_span,
337 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` because of this",
ty))
})format!("expected `{ty}` because of this"),
338 );
339 } else if is_question_mark {
340 let main_trait_predicate =
341 self.tcx.short_string(main_trait_predicate, err.long_ty_path());
342 err.span_label(
343 ret_span,
344 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required `{0}` because of this",
main_trait_predicate))
})format!("required `{main_trait_predicate}` because of this"),
345 );
346 }
347 }
348
349 if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Tuple) {
350 self.add_tuple_trait_message(
351 obligation.cause.code().peel_derives(),
352 &mut err,
353 );
354 }
355
356 let explanation = get_explanation_based_on_obligation(
357 self.tcx,
358 &obligation,
359 leaf_trait_predicate,
360 pre_message,
361 err.long_ty_path(),
362 );
363
364 self.check_for_binding_assigned_block_without_tail_expression(
365 &obligation,
366 &mut err,
367 leaf_trait_predicate,
368 );
369 self.suggest_add_result_as_return_type(
370 &obligation,
371 &mut err,
372 leaf_trait_predicate,
373 );
374
375 if self.suggest_add_reference_to_arg(
376 &obligation,
377 &mut err,
378 leaf_trait_predicate,
379 have_alt_message,
380 ) {
381 self.note_obligation_cause(&mut err, &obligation);
382 return err.emit();
383 }
384
385 let ty_span = match leaf_trait_predicate.self_ty().skip_binder().kind() {
386 ty::Adt(def, _)
387 if def.did().is_local()
388 && !self
389 .can_suggest_derive(&obligation, leaf_trait_predicate) =>
390 {
391 self.tcx.def_span(def.did())
392 }
393 _ => DUMMY_SP,
394 };
395 if let Some(s) = label {
396 err.span_label(span, s);
399 if !#[allow(non_exhaustive_omitted_patterns)] match leaf_trait_predicate.skip_binder().self_ty().kind()
{
ty::Param(_) => true,
_ => false,
}matches!(leaf_trait_predicate.skip_binder().self_ty().kind(), ty::Param(_))
400 && !self.tcx.is_diagnostic_item(sym::FromResidual, leaf_trait_predicate.def_id())
404 {
407 if ty_span == DUMMY_SP {
410 err.help(explanation);
411 } else {
412 err.span_help(ty_span, explanation);
413 }
414 }
415 } else if let Some(custom_explanation) = safe_transmute_explanation {
416 err.span_label(span, custom_explanation);
417 } else if (explanation.len() > self.tcx.sess.diagnostic_width()
418 || ty_span != DUMMY_SP)
419 && !noted_missing_impl
420 {
421 err.span_label(span, "unsatisfied trait bound");
424
425 if ty_span == DUMMY_SP {
428 err.help(explanation);
429 } else {
430 err.span_help(ty_span, explanation);
431 }
432 } else {
433 err.span_label(span, explanation);
434 }
435
436 if let ObligationCauseCode::Coercion { source, target } =
437 *obligation.cause.code().peel_derives()
438 {
439 if self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Sized)
440 {
441 self.suggest_borrowing_for_object_cast(
442 &mut err,
443 root_obligation,
444 source,
445 target,
446 );
447 }
448 }
449
450 if let Some((msg, span)) = type_def {
451 err.span_label(span, msg);
452 }
453 let derive_suggestion_will_be_shown = main_trait_predicate
461 == leaf_trait_predicate
462 && self.can_suggest_derive(&obligation, leaf_trait_predicate);
463 if !derive_suggestion_will_be_shown {
464 for note in notes {
465 err.note(note);
468 }
469 }
470 if let Some(s) = parent_label {
471 let body = obligation.cause.body_def_id;
472 err.span_label(tcx.def_span(body), s);
473 }
474
475 self.suggest_floating_point_literal(
476 &obligation,
477 &mut err,
478 leaf_trait_predicate,
479 );
480 self.suggest_dereferencing_index(
481 &obligation,
482 &mut err,
483 leaf_trait_predicate,
484 );
485 suggested |=
486 self.suggest_dereferences(&obligation, &mut err, leaf_trait_predicate);
487 suggested |=
488 self.suggest_fn_call(&obligation, &mut err, leaf_trait_predicate);
489 suggested |= self.suggest_cast_to_fn_pointer(
490 &obligation,
491 &mut err,
492 leaf_trait_predicate,
493 main_trait_predicate,
494 span,
495 );
496 suggested |= self.suggest_remove_reference(
497 &obligation,
498 &mut err,
499 leaf_trait_predicate,
500 );
501 suggested |= self.suggest_semicolon_removal(
502 &obligation,
503 &mut err,
504 span,
505 leaf_trait_predicate,
506 );
507 self.note_different_trait_with_same_name(
508 &mut err,
509 &obligation,
510 leaf_trait_predicate,
511 );
512 self.note_adt_version_mismatch(&mut err, leaf_trait_predicate);
513 self.suggest_remove_await(&obligation, &mut err);
514 self.suggest_derive(&obligation, &mut err, leaf_trait_predicate);
515
516 if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Try) {
517 self.suggest_await_before_try(
518 &mut err,
519 &obligation,
520 leaf_trait_predicate,
521 span,
522 );
523 }
524
525 if self.suggest_add_clone_to_arg(
526 &obligation,
527 &mut err,
528 leaf_trait_predicate,
529 ) {
530 return err.emit();
531 }
532
533 if self.suggest_impl_trait(&mut err, &obligation, leaf_trait_predicate) {
534 return err.emit();
535 }
536
537 if is_unsize {
538 err.note(
541 "all implementations of `Unsize` are provided \
542 automatically by the compiler, see \
543 <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
544 for more information",
545 );
546 }
547
548 let is_fn_trait = tcx.is_fn_trait(leaf_trait_predicate.def_id());
549 let is_target_feature_fn = if let ty::FnDef(def_id, _) =
550 *leaf_trait_predicate.skip_binder().self_ty().kind()
551 {
552 !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
553 } else {
554 false
555 };
556 if is_fn_trait && is_target_feature_fn {
557 err.note(
558 "`#[target_feature]` functions do not implement the `Fn` traits",
559 );
560 err.note(
561 "try casting the function to a `fn` pointer or wrapping it in a closure",
562 );
563 }
564
565 self.note_field_shadowed_by_private_candidate_in_cause(
566 &mut err,
567 &obligation.cause,
568 obligation.param_env,
569 );
570 self.try_to_add_help_message(
571 &root_obligation,
572 &obligation,
573 leaf_trait_predicate,
574 &mut err,
575 span,
576 is_fn_trait,
577 suggested,
578 );
579
580 if !is_unsize {
583 self.suggest_change_mut(&obligation, &mut err, leaf_trait_predicate);
584 }
585
586 if leaf_trait_predicate.skip_binder().self_ty().is_never()
591 && self.diverging_fallback_has_occurred
592 {
593 let predicate = leaf_trait_predicate.map_bound(|trait_pred| {
594 trait_pred.with_replaced_self_ty(self.tcx, tcx.types.unit)
595 });
596 let unit_obligation = obligation.with(tcx, predicate);
597 if self.predicate_may_hold(&unit_obligation) {
598 err.note(
599 "this error might have been caused by changes to \
600 Rust's type-inference algorithm (see issue #148922 \
601 <https://github.com/rust-lang/rust/issues/148922> \
602 for more information)",
603 );
604 err.help(
605 "you might have intended to use the type `()` here instead",
606 );
607 }
608 }
609
610 self.explain_hrtb_projection(
611 &mut err,
612 leaf_trait_predicate,
613 obligation.param_env,
614 &obligation.cause,
615 );
616 self.suggest_desugaring_async_fn_in_trait(&mut err, main_trait_predicate);
617
618 let in_std_macro =
624 match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
625 Some(macro_def_id) => {
626 let crate_name = tcx.crate_name(macro_def_id.krate);
627 STDLIB_STABLE_CRATES.contains(&crate_name)
628 }
629 None => false,
630 };
631
632 if in_std_macro
633 && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id())
{
Some(sym::Debug | sym::Display) => true,
_ => false,
}matches!(
634 self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id()),
635 Some(sym::Debug | sym::Display)
636 )
637 {
638 return err.emit();
639 }
640
641 err
642 }
643
644 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => self
645 .report_host_effect_error(
646 bound_predicate.rebind(predicate),
647 &obligation,
648 span,
649 ),
650
651 ty::PredicateKind::Subtype(predicate) => {
652 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("subtype requirement gave wrong error: `{0:?}`", predicate))span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
656 }
657
658 ty::PredicateKind::Coerce(predicate) => {
659 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("coerce requirement gave wrong error: `{0:?}`", predicate))span_bug!(span, "coerce requirement gave wrong error: `{:?}`", predicate)
663 }
664
665 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..))
666 | ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..)) => {
667 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("outlives clauses should not error outside borrowck. obligation: `{0:?}`",
obligation))span_bug!(
668 span,
669 "outlives clauses should not error outside borrowck. obligation: `{:?}`",
670 obligation
671 )
672 }
673
674 ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => {
675 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("projection clauses should be implied from elsewhere. obligation: `{0:?}`",
obligation))span_bug!(
676 span,
677 "projection clauses should be implied from elsewhere. obligation: `{:?}`",
678 obligation
679 )
680 }
681
682 ty::PredicateKind::DynCompatible(trait_def_id) => {
683 let violations = self.tcx.dyn_compatibility_violations(trait_def_id);
684 let mut err = report_dyn_incompatibility(
685 self.tcx,
686 span,
687 None,
688 trait_def_id,
689 violations,
690 );
691 if let hir::Node::Item(item) =
692 self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
693 && let hir::ItemKind::Impl(impl_) = item.kind
694 && let None = impl_.of_trait
695 && let hir::TyKind::TraitObject(_, tagged_ptr) = impl_.self_ty.kind
696 && let TraitObjectSyntax::None = tagged_ptr.tag()
697 && impl_.self_ty.span.edition().at_least_rust_2021()
698 {
699 err.downgrade_to_delayed_bug();
702 }
703 err
704 }
705
706 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(ty)) => {
707 let ty = self.resolve_vars_if_possible(ty);
708 if self.next_trait_solver() {
709 if let Err(guar) = ty.error_reported() {
710 return guar;
711 }
712
713 self.dcx().struct_span_err(
716 span,
717 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the type `{0}` is not well-formed",
ty))
})format!("the type `{ty}` is not well-formed"),
718 )
719 } else {
720 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("WF predicate not satisfied for {0:?}", ty));span_bug!(span, "WF predicate not satisfied for {:?}", ty);
726 }
727 }
728
729 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
734 | ty::PredicateKind::ConstEquate { .. }
735 | ty::PredicateKind::Ambiguous
736 | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature { .. })
737 | ty::PredicateKind::NormalizesTo { .. }
738 | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType { .. }) => {
739 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("Unexpected `Predicate` for `SelectionError`: `{0:?}`",
obligation))span_bug!(
740 span,
741 "Unexpected `Predicate` for `SelectionError`: `{:?}`",
742 obligation
743 )
744 }
745 }
746 }
747
748 SelectionError::SignatureMismatch(SignatureMismatchData {
749 found_trait_ref,
750 expected_trait_ref,
751 terr: terr @ TypeError::CyclicTy(_),
752 }) => self.report_cyclic_signature_error(
753 &obligation,
754 found_trait_ref,
755 expected_trait_ref,
756 terr,
757 ),
758 SelectionError::SignatureMismatch(SignatureMismatchData {
759 found_trait_ref,
760 expected_trait_ref,
761 terr: _,
762 }) => {
763 match self.report_signature_mismatch_error(
764 &obligation,
765 span,
766 found_trait_ref,
767 expected_trait_ref,
768 ) {
769 Ok(err) => err,
770 Err(guar) => return guar,
771 }
772 }
773
774 SelectionError::TraitDynIncompatible(did) => {
775 let violations = self.tcx.dyn_compatibility_violations(did);
776 report_dyn_incompatibility(self.tcx, span, None, did, violations)
777 }
778
779 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
780 ::rustc_middle::util::bug::bug_fmt(format_args!("MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"))bug!(
781 "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
782 )
783 }
784 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
785 match self.report_not_const_evaluatable_error(&obligation, span) {
786 Ok(err) => err,
787 Err(guar) => return guar,
788 }
789 }
790
791 SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(guar))
793 | SelectionError::Overflow(OverflowError::Error(guar)) => {
794 self.set_tainted_by_errors(guar);
795 return guar;
796 }
797
798 SelectionError::Overflow(_) => {
799 ::rustc_middle::util::bug::bug_fmt(format_args!("overflow should be handled before the `report_selection_error` path"));bug!("overflow should be handled before the `report_selection_error` path");
800 }
801
802 SelectionError::ConstArgHasWrongType { ct, ct_ty, expected_ty } => {
803 let expected_ty_str = self.tcx.short_string(expected_ty, &mut long_ty_file);
804 let ct_str = self.tcx.short_string(ct, &mut long_ty_file);
805 let mut diag = self.dcx().struct_span_err(
806 span,
807 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the constant `{0}` is not of type `{1}`",
ct_str, expected_ty_str))
})format!("the constant `{ct_str}` is not of type `{expected_ty_str}`"),
808 );
809 diag.long_ty_path = long_ty_file;
810
811 self.note_type_err(
812 &mut diag,
813 &obligation.cause,
814 None,
815 None,
816 TypeError::Sorts(ty::error::ExpectedFound::new(expected_ty, ct_ty)),
817 false,
818 None,
819 );
820 diag
821 }
822 };
823
824 self.note_obligation_cause(&mut err, &obligation);
825 err.emit()
826 }
827}
828
829impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
830 pub(super) fn apply_do_not_recommend(
831 &self,
832 obligation: &mut PredicateObligation<'tcx>,
833 root_obligation: &PredicateObligation<'tcx>,
834 ) -> bool {
835 let mut base_cause = obligation.cause.code().clone();
836 let mut applied_do_not_recommend = false;
837 loop {
838 if let ObligationCauseCode::ImplDerived(ref c) = base_cause {
839 if self.tcx.do_not_recommend_impl(c.impl_or_alias_def_id) {
840 let code = (*c.derived.parent_code).clone();
841 if code == *root_obligation.cause.code()
844 && root_obligation.cause.span.eq_ctxt(obligation.cause.span)
845 && !root_obligation.cause.span.contains(obligation.cause.span)
846 {
847 obligation.cause.span = root_obligation.cause.span;
848 }
849 obligation.cause.map_code(|_| code);
850 obligation.predicate = c.derived.parent_trait_pred.upcast(self.tcx);
851 applied_do_not_recommend = true;
852 }
853 }
854 if let Some(parent_cause) = base_cause.parent() {
855 base_cause = parent_cause.clone();
856 } else {
857 break;
858 }
859 }
860
861 applied_do_not_recommend
862 }
863
864 fn report_host_effect_error(
865 &self,
866 predicate: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
867 main_obligation: &PredicateObligation<'tcx>,
868 span: Span,
869 ) -> Diag<'a> {
870 let trait_ref = predicate.map_bound(|predicate| ty::TraitPredicate {
874 trait_ref: predicate.trait_ref,
875 polarity: ty::PredicatePolarity::Positive,
876 });
877 let mut file = None;
878
879 let err_msg = self.get_standard_error_message(
880 trait_ref,
881 Some(predicate.constness()),
882 String::new(),
883 &mut file,
884 );
885 let mut diag = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", err_msg))
})).with_code(E0277)
}struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg);
886 *diag.long_ty_path() = file;
887 let obligation = Obligation::new(
888 self.tcx,
889 ObligationCause::dummy(),
890 main_obligation.param_env,
891 trait_ref,
892 );
893 if !self.predicate_may_hold(&obligation) {
894 diag.downgrade_to_delayed_bug();
895 }
896
897 if let Ok(Some(ImplSource::UserDefined(impl_data))) =
898 self.enter_forall(trait_ref, |trait_ref_for_select| {
899 SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref_for_select))
900 })
901 {
902 let impl_did = impl_data.impl_def_id;
903 let trait_did = trait_ref.def_id();
904 let impl_span = self.tcx.def_span(impl_did);
905 let trait_name = self.tcx.item_name(trait_did);
906
907 if self.tcx.is_const_trait(trait_did) && !self.tcx.is_const_trait_impl(impl_did) {
908 if !impl_did.is_local() {
909 diag.span_note(
910 impl_span,
911 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait `{0}` is implemented but not `const`",
trait_name))
})format!("trait `{trait_name}` is implemented but not `const`"),
912 );
913 }
914
915 if let Some(command) =
916 {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(impl_did, &self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(OnConst { directive, .. }) => {
break 'done Some(directive.as_deref());
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.tcx, impl_did, OnConst {directive, ..} => directive.as_deref())
917 .flatten()
918 {
919 let (_, format_args) = self.on_unimplemented_components(
920 trait_ref,
921 main_obligation,
922 diag.long_ty_path(),
923 );
924 let CustomDiagnostic { message, label, notes, parent_label: _ } =
925 command.eval(None, &format_args);
926
927 if let Some(message) = message {
928 diag.primary_message(message);
929 }
930 if let Some(label) = label {
931 diag.span_label(span, label);
932 }
933 for note in notes {
934 diag.note(note);
935 }
936 } else if let Some(impl_did) = impl_did.as_local()
937 && let item = self.tcx.hir_expect_item(impl_did)
938 && let hir::ItemKind::Impl(item) = item.kind
939 && let Some(of_trait) = item.of_trait
940 {
941 diag.span_suggestion_verbose(
943 of_trait.trait_ref.path.span.shrink_to_lo(),
944 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("make the `impl` of trait `{0}` `const`",
trait_name))
})format!("make the `impl` of trait `{trait_name}` `const`"),
945 "const ".to_string(),
946 Applicability::MaybeIncorrect,
947 );
948 }
949 }
950 } else if let ty::Param(param) = trait_ref.self_ty().skip_binder().kind()
951 && let Some(generics) =
952 self.tcx.hir_node_by_def_id(main_obligation.cause.body_def_id).generics()
953 {
954 let constraint = {
let _guard = NoTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[const] {0}",
trait_ref.map_bound(|tr|
tr.trait_ref).print_trait_sugared()))
})
}ty::print::with_no_trimmed_paths!(format!(
955 "[const] {}",
956 trait_ref.map_bound(|tr| tr.trait_ref).print_trait_sugared(),
957 ));
958 ty::suggest_constraining_type_param(
959 self.tcx,
960 generics,
961 &mut diag,
962 param.name.as_str(),
963 &constraint,
964 Some(trait_ref.def_id()),
965 None,
966 );
967 }
968 diag
969 }
970
971 fn emit_specialized_closure_kind_error(
972 &self,
973 obligation: &PredicateObligation<'tcx>,
974 mut trait_pred: ty::PolyTraitPredicate<'tcx>,
975 ) -> Option<ErrorGuaranteed> {
976 if self.tcx.is_lang_item(trait_pred.def_id(), LangItem::AsyncFnKindHelper) {
979 let mut code = obligation.cause.code();
980 if let ObligationCauseCode::FunctionArg { parent_code, .. } = code {
982 code = &**parent_code;
983 }
984 if let Some((_, Some(parent))) = code.parent_with_predicate() {
986 trait_pred = parent;
987 }
988 }
989
990 let self_ty = trait_pred.self_ty().skip_binder();
991
992 let (expected_kind, trait_prefix) =
993 if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) {
994 (expected_kind, "")
995 } else if let Some(expected_kind) =
996 self.tcx.async_fn_trait_kind_from_def_id(trait_pred.def_id())
997 {
998 (expected_kind, "Async")
999 } else {
1000 return None;
1001 };
1002
1003 let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() {
1004 ty::Closure(def_id, args) => {
1005 (def_id, args.as_closure().sig().map_bound(|sig| sig.inputs()[0]), false)
1006 }
1007 ty::CoroutineClosure(def_id, args) => (
1008 def_id,
1009 args.as_coroutine_closure()
1010 .coroutine_closure_sig()
1011 .map_bound(|sig| sig.tupled_inputs_ty),
1012 !args.as_coroutine_closure().tupled_upvars_ty().is_ty_var()
1013 && args.as_coroutine_closure().has_self_borrows(),
1014 ),
1015 _ => return None,
1016 };
1017
1018 let expected_args = trait_pred.map_bound(|trait_pred| trait_pred.trait_ref.args.type_at(1));
1019
1020 if self.enter_forall(found_args, |found_args| {
1023 self.enter_forall(expected_args, |expected_args| {
1024 !self.can_eq(obligation.param_env, expected_args, found_args)
1025 })
1026 }) {
1027 return None;
1028 }
1029
1030 if let Some(found_kind) = self.closure_kind(self_ty)
1031 && !found_kind.extends(expected_kind)
1032 {
1033 let mut err = self.report_closure_error(
1034 &obligation,
1035 closure_def_id,
1036 found_kind,
1037 expected_kind,
1038 trait_prefix,
1039 );
1040 self.note_obligation_cause(&mut err, &obligation);
1041 return Some(err.emit());
1042 }
1043
1044 if has_self_borrows && expected_kind != ty::ClosureKind::FnOnce {
1048 let coro_kind = match self
1049 .tcx
1050 .coroutine_kind(self.tcx.coroutine_for_closure(closure_def_id))
1051 .unwrap()
1052 {
1053 rustc_hir::CoroutineKind::Desugared(desugaring, _) => desugaring.to_string(),
1054 coro => coro.to_string(),
1055 };
1056 let mut err = self.dcx().create_err(CoroClosureNotFn {
1057 span: self.tcx.def_span(closure_def_id),
1058 kind: expected_kind.as_str(),
1059 coro_kind,
1060 });
1061 self.note_obligation_cause(&mut err, &obligation);
1062 return Some(err.emit());
1063 }
1064
1065 None
1066 }
1067
1068 fn fn_arg_obligation(
1069 &self,
1070 obligation: &PredicateObligation<'tcx>,
1071 ) -> Result<(), ErrorGuaranteed> {
1072 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1073 && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
1074 && let arg = arg.peel_borrows()
1075 && let hir::ExprKind::Path(hir::QPath::Resolved(
1076 None,
1077 hir::Path { res: hir::def::Res::Local(hir_id), .. },
1078 )) = arg.kind
1079 && let Node::Pat(pat) = self.tcx.hir_node(*hir_id)
1080 && let Some((preds, guar)) = self.reported_trait_errors.borrow().get(&pat.span)
1081 && preds.contains(&obligation.as_goal())
1082 {
1083 return Err(*guar);
1084 }
1085 Ok(())
1086 }
1087
1088 fn detect_negative_literal(
1089 &self,
1090 obligation: &PredicateObligation<'tcx>,
1091 trait_pred: ty::PolyTraitPredicate<'tcx>,
1092 err: &mut Diag<'_>,
1093 ) -> bool {
1094 if let ObligationCauseCode::UnOp { hir_id, .. } = obligation.cause.code()
1095 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1096 && let hir::ExprKind::Unary(hir::UnOp::Neg, inner) = expr.kind
1097 && let hir::ExprKind::Lit(lit) = inner.kind
1098 && let LitKind::Int(_, LitIntType::Unsuffixed) = lit.node
1099 {
1100 err.span_suggestion_verbose(
1101 lit.span.shrink_to_hi(),
1102 "consider specifying an integer type that can be negative",
1103 match trait_pred.skip_binder().self_ty().kind() {
1104 ty::Uint(ty::UintTy::Usize) => "isize",
1105 ty::Uint(ty::UintTy::U8) => "i8",
1106 ty::Uint(ty::UintTy::U16) => "i16",
1107 ty::Uint(ty::UintTy::U32) => "i32",
1108 ty::Uint(ty::UintTy::U64) => "i64",
1109 ty::Uint(ty::UintTy::U128) => "i128",
1110 _ => "i64",
1111 }
1112 .to_string(),
1113 Applicability::MaybeIncorrect,
1114 );
1115 return true;
1116 }
1117 false
1118 }
1119
1120 fn try_conversion_context(
1124 &self,
1125 obligation: &PredicateObligation<'tcx>,
1126 trait_pred: ty::PolyTraitPredicate<'tcx>,
1127 err: &mut Diag<'_>,
1128 ) -> (bool, bool) {
1129 let span = obligation.cause.span;
1130 struct FindMethodSubexprOfTry {
1132 search_span: Span,
1133 }
1134 impl<'v> Visitor<'v> for FindMethodSubexprOfTry {
1135 type Result = ControlFlow<&'v hir::Expr<'v>>;
1136 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
1137 if let hir::ExprKind::Match(expr, _arms, hir::MatchSource::TryDesugar(_)) = ex.kind
1138 && ex.span.with_lo(ex.span.hi() - BytePos(1)).source_equal(self.search_span)
1139 && let hir::ExprKind::Call(_, [expr, ..]) = expr.kind
1140 {
1141 ControlFlow::Break(expr)
1142 } else {
1143 hir::intravisit::walk_expr(self, ex)
1144 }
1145 }
1146 }
1147 let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_def_id);
1148 let Some(body_id) = self.tcx.hir_node(hir_id).body_id() else { return (false, false) };
1149 let ControlFlow::Break(expr) =
1150 (FindMethodSubexprOfTry { search_span: span }).visit_body(self.tcx.hir_body(body_id))
1151 else {
1152 return (false, false);
1153 };
1154 let Some(typeck) = &self.typeck_results else {
1155 return (false, false);
1156 };
1157 let ObligationCauseCode::QuestionMark = obligation.cause.code().peel_derives() else {
1158 return (false, false);
1159 };
1160 let self_ty = trait_pred.skip_binder().self_ty();
1161 let found_ty = trait_pred.skip_binder().trait_ref.args.get(1).and_then(|a| a.as_type());
1162 let noted_missing_impl =
1163 self.note_missing_impl_for_question_mark(err, self_ty, found_ty, trait_pred);
1164
1165 let mut prev_ty = self.resolve_vars_if_possible(
1166 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1167 );
1168
1169 let get_e_type = |prev_ty: Ty<'tcx>| -> Option<Ty<'tcx>> {
1173 let ty::Adt(def, args) = prev_ty.kind() else {
1174 return None;
1175 };
1176 let Some(arg) = args.get(1) else {
1177 return None;
1178 };
1179 if !self.tcx.is_diagnostic_item(sym::Result, def.did()) {
1180 return None;
1181 }
1182 arg.as_type()
1183 };
1184
1185 let mut suggested = false;
1186 let mut chain = ::alloc::vec::Vec::new()vec![];
1187
1188 let mut expr = expr;
1190 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
1191 expr = rcvr_expr;
1195 chain.push((span, prev_ty));
1196
1197 let next_ty = self.resolve_vars_if_possible(
1198 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1199 );
1200
1201 let is_diagnostic_item = |symbol: Symbol, ty: Ty<'tcx>| {
1202 let ty::Adt(def, _) = ty.kind() else {
1203 return false;
1204 };
1205 self.tcx.is_diagnostic_item(symbol, def.did())
1206 };
1207 if let Some(ty) = get_e_type(prev_ty)
1211 && let Some(found_ty) = found_ty
1212 && (
1217 ( path_segment.ident.name == sym::map_err
1219 && is_diagnostic_item(sym::Result, next_ty)
1220 ) || ( path_segment.ident.name == sym::ok_or_else
1222 && is_diagnostic_item(sym::Option, next_ty)
1223 )
1224 )
1225 && let ty::Tuple(tys) = found_ty.kind()
1227 && tys.is_empty()
1228 && self.can_eq(obligation.param_env, ty, found_ty)
1230 && let [arg] = args
1232 && let hir::ExprKind::Closure(closure) = arg.kind
1233 && let body = self.tcx.hir_body(closure.body)
1235 && let hir::ExprKind::Block(block, _) = body.value.kind
1236 && let None = block.expr
1237 && let [.., stmt] = block.stmts
1239 && let hir::StmtKind::Semi(expr) = stmt.kind
1240 && let expr_ty = self.resolve_vars_if_possible(
1241 typeck.expr_ty_adjusted_opt(expr)
1242 .unwrap_or(Ty::new_misc_error(self.tcx)),
1243 )
1244 && self
1245 .infcx
1246 .type_implements_trait(
1247 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1248 [self_ty, expr_ty],
1249 obligation.param_env,
1250 )
1251 .must_apply_modulo_regions()
1252 {
1253 suggested = true;
1254 err.span_suggestion_short(
1255 stmt.span.with_lo(expr.span.hi()),
1256 "remove this semicolon",
1257 String::new(),
1258 Applicability::MachineApplicable,
1259 );
1260 }
1261
1262 prev_ty = next_ty;
1263
1264 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1265 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
1266 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
1267 {
1268 let parent = self.tcx.parent_hir_node(binding.hir_id);
1269 if let hir::Node::LetStmt(local) = parent
1271 && let Some(binding_expr) = local.init
1272 {
1273 expr = binding_expr;
1275 }
1276 if let hir::Node::Param(_param) = parent {
1277 break;
1279 }
1280 }
1281 }
1282 prev_ty = self.resolve_vars_if_possible(
1286 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1287 );
1288 chain.push((expr.span, prev_ty));
1289
1290 let mut prev = None;
1291 let mut iter = chain.into_iter().rev().peekable();
1292 while let Some((span, err_ty)) = iter.next() {
1293 let is_last = iter.peek().is_none();
1294 let err_ty = get_e_type(err_ty);
1295 let err_ty = match (err_ty, prev) {
1296 (Some(err_ty), Some(prev)) if !self.can_eq(obligation.param_env, err_ty, prev) => {
1297 err_ty
1298 }
1299 (Some(err_ty), None) => err_ty,
1300 _ => {
1301 prev = err_ty;
1302 continue;
1303 }
1304 };
1305
1306 let implements_from = self
1307 .infcx
1308 .type_implements_trait(
1309 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1310 [self_ty, err_ty],
1311 obligation.param_env,
1312 )
1313 .must_apply_modulo_regions();
1314
1315 let err_ty_str = self.tcx.short_string(err_ty, err.long_ty_path());
1316 let label = if !implements_from && is_last {
1317 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this can\'t be annotated with `?` because it has type `Result<_, {0}>`",
err_ty_str))
})format!(
1318 "this can't be annotated with `?` because it has type `Result<_, {err_ty_str}>`"
1319 )
1320 } else {
1321 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this has type `Result<_, {0}>`",
err_ty_str))
})format!("this has type `Result<_, {err_ty_str}>`")
1322 };
1323
1324 if !suggested || !implements_from {
1325 err.span_label(span, label);
1326 }
1327 prev = Some(err_ty);
1328 }
1329 (suggested, noted_missing_impl)
1330 }
1331
1332 fn note_missing_impl_for_question_mark(
1333 &self,
1334 err: &mut Diag<'_>,
1335 self_ty: Ty<'_>,
1336 found_ty: Option<Ty<'_>>,
1337 trait_pred: ty::PolyTraitPredicate<'tcx>,
1338 ) -> bool {
1339 match (self_ty.kind(), found_ty) {
1340 (ty::Adt(def, _), Some(ty))
1341 if let ty::Adt(found, _) = ty.kind()
1342 && def.did().is_local()
1343 && found.did().is_local() =>
1344 {
1345 err.span_note(
1346 self.tcx.def_span(def.did()),
1347 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` needs to implement `From<{1}>`",
self_ty, ty))
})format!("`{self_ty}` needs to implement `From<{ty}>`"),
1348 );
1349 }
1350 (ty::Adt(def, _), None) if def.did().is_local() => {
1351 let trait_path = self.tcx.short_string(
1352 trait_pred.skip_binder().trait_ref.print_only_trait_path(),
1353 err.long_ty_path(),
1354 );
1355 err.span_note(
1356 self.tcx.def_span(def.did()),
1357 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` needs to implement `{1}`",
self_ty, trait_path))
})format!("`{self_ty}` needs to implement `{trait_path}`"),
1358 );
1359 }
1360 (ty::Adt(def, _), Some(ty)) if def.did().is_local() => {
1361 err.span_note(
1362 self.tcx.def_span(def.did()),
1363 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` needs to implement `From<{1}>`",
self_ty, ty))
})format!("`{self_ty}` needs to implement `From<{ty}>`"),
1364 );
1365 }
1366 (_, Some(ty))
1367 if let ty::Adt(def, _) = ty.kind()
1368 && def.did().is_local() =>
1369 {
1370 err.span_note(
1371 self.tcx.def_span(def.did()),
1372 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` needs to implement `Into<{1}>`",
ty, self_ty))
})format!("`{ty}` needs to implement `Into<{self_ty}>`"),
1373 );
1374 }
1375 _ => return false,
1376 }
1377 true
1378 }
1379
1380 fn report_const_param_not_wf(
1381 &self,
1382 ty: Ty<'tcx>,
1383 obligation: &PredicateObligation<'tcx>,
1384 ) -> Diag<'a> {
1385 let def_id = obligation.cause.body_def_id;
1386 let span = self.tcx.ty_span(def_id);
1387
1388 let mut file = None;
1389 let ty_str = self.tcx.short_string(ty, &mut file);
1390 let mut diag = match ty.kind() {
1391 ty::Float(_) => {
1392 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
ty_str))
})).with_code(E0741)
}struct_span_code_err!(
1393 self.dcx(),
1394 span,
1395 E0741,
1396 "`{ty_str}` is forbidden as the type of a const generic parameter",
1397 )
1398 }
1399 ty::FnPtr(..) => {
1400 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("using function pointers as const generic parameters is forbidden"))
})).with_code(E0741)
}struct_span_code_err!(
1401 self.dcx(),
1402 span,
1403 E0741,
1404 "using function pointers as const generic parameters is forbidden",
1405 )
1406 }
1407 ty::RawPtr(_, _) => {
1408 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("using raw pointers as const generic parameters is forbidden"))
})).with_code(E0741)
}struct_span_code_err!(
1409 self.dcx(),
1410 span,
1411 E0741,
1412 "using raw pointers as const generic parameters is forbidden",
1413 )
1414 }
1415 ty::Adt(def, _) => {
1416 let mut diag = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
ty_str))
})).with_code(E0741)
}struct_span_code_err!(
1418 self.dcx(),
1419 span,
1420 E0741,
1421 "`{ty_str}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
1422 );
1423 if let Some(span) = self.tcx.hir_span_if_local(def.did())
1426 && obligation.cause.code().parent().is_none()
1427 {
1428 if ty.is_structural_eq_shallow(self.tcx) {
1429 diag.span_suggestion(
1430 span.shrink_to_lo(),
1431 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy)]` to the {0}",
def.descr()))
})format!("add `#[derive(ConstParamTy)]` to the {}", def.descr()),
1432 "#[derive(ConstParamTy)]\n",
1433 Applicability::MachineApplicable,
1434 );
1435 } else {
1436 diag.span_suggestion(
1439 span.shrink_to_lo(),
1440 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {0}",
def.descr()))
})format!(
1441 "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {}",
1442 def.descr()
1443 ),
1444 "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1445 Applicability::MachineApplicable,
1446 );
1447 }
1448 }
1449 diag
1450 }
1451 _ => {
1452 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` can\'t be used as a const parameter type",
ty_str))
})).with_code(E0741)
}struct_span_code_err!(
1453 self.dcx(),
1454 span,
1455 E0741,
1456 "`{ty_str}` can't be used as a const parameter type",
1457 )
1458 }
1459 };
1460 diag.long_ty_path = file;
1461
1462 let mut code = obligation.cause.code();
1463 let mut pred = obligation.predicate.as_trait_clause();
1464 while let Some((next_code, next_pred)) = code.parent_with_predicate() {
1465 if let Some(pred) = pred {
1466 self.enter_forall(pred, |pred| {
1467 let ty = self.tcx.short_string(pred.self_ty(), diag.long_ty_path());
1468 let trait_path = self
1469 .tcx
1470 .short_string(pred.print_modifiers_and_trait_path(), diag.long_ty_path());
1471 diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` must implement `{1}`, but it does not",
ty, trait_path))
})format!("`{ty}` must implement `{trait_path}`, but it does not"));
1472 })
1473 }
1474 code = next_code;
1475 pred = next_pred;
1476 }
1477
1478 diag
1479 }
1480}
1481
1482impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
1483 fn can_match_trait(
1484 &self,
1485 param_env: ty::ParamEnv<'tcx>,
1486 goal: ty::TraitPredicate<'tcx>,
1487 assumption: ty::PolyTraitPredicate<'tcx>,
1488 ) -> bool {
1489 if goal.polarity != assumption.polarity() {
1491 return false;
1492 }
1493
1494 let trait_assumption = self.instantiate_binder_with_fresh_vars(
1495 DUMMY_SP,
1496 infer::BoundRegionConversionTime::HigherRankedType,
1497 assumption,
1498 );
1499
1500 self.can_eq(param_env, goal.trait_ref, trait_assumption.trait_ref)
1501 }
1502
1503 fn can_match_host_effect(
1504 &self,
1505 param_env: ty::ParamEnv<'tcx>,
1506 goal: ty::HostEffectPredicate<'tcx>,
1507 assumption: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
1508 ) -> bool {
1509 let assumption = self.instantiate_binder_with_fresh_vars(
1510 DUMMY_SP,
1511 infer::BoundRegionConversionTime::HigherRankedType,
1512 assumption,
1513 );
1514
1515 assumption.constness.satisfies(goal.constness)
1516 && self.can_eq(param_env, goal.trait_ref, assumption.trait_ref)
1517 }
1518
1519 fn as_host_effect_clause(
1520 predicate: ty::Predicate<'tcx>,
1521 ) -> Option<ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>> {
1522 predicate.as_clause().and_then(|clause| match clause.kind().skip_binder() {
1523 ty::ClauseKind::HostEffect(pred) => Some(clause.kind().rebind(pred)),
1524 _ => None,
1525 })
1526 }
1527
1528 fn can_match_projection(
1529 &self,
1530 param_env: ty::ParamEnv<'tcx>,
1531 goal: ty::ProjectionPredicate<'tcx>,
1532 assumption: ty::PolyProjectionPredicate<'tcx>,
1533 ) -> bool {
1534 let assumption = self.instantiate_binder_with_fresh_vars(
1535 DUMMY_SP,
1536 infer::BoundRegionConversionTime::HigherRankedType,
1537 assumption,
1538 );
1539
1540 self.can_eq(param_env, goal.projection_term, assumption.projection_term)
1541 && self.can_eq(param_env, goal.term, assumption.term)
1542 }
1543
1544 x;#[instrument(level = "debug", skip(self), ret)]
1547 pub(super) fn error_implies(
1548 &self,
1549 cond: Goal<'tcx, ty::Predicate<'tcx>>,
1550 error: Goal<'tcx, ty::Predicate<'tcx>>,
1551 ) -> bool {
1552 if cond == error {
1553 return true;
1554 }
1555
1556 if cond.param_env != error.param_env {
1560 return false;
1561 }
1562 let param_env = error.param_env;
1563
1564 if let Some(error) = error.predicate.as_trait_clause() {
1565 self.enter_forall(error, |error| {
1566 elaborate(self.tcx, std::iter::once(cond.predicate))
1567 .filter_map(|implied| implied.as_trait_clause())
1568 .any(|implied| self.can_match_trait(param_env, error, implied))
1569 })
1570 } else if let Some(error) = Self::as_host_effect_clause(error.predicate) {
1571 self.enter_forall(error, |error| {
1572 elaborate(self.tcx, std::iter::once(cond.predicate))
1573 .filter_map(Self::as_host_effect_clause)
1574 .any(|implied| self.can_match_host_effect(param_env, error, implied))
1575 })
1576 } else if let Some(error) = error.predicate.as_projection_clause() {
1577 self.enter_forall(error, |error| {
1578 elaborate(self.tcx, std::iter::once(cond.predicate))
1579 .filter_map(|implied| implied.as_projection_clause())
1580 .any(|implied| self.can_match_projection(param_env, error, implied))
1581 })
1582 } else {
1583 false
1584 }
1585 }
1586
1587 #[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_projection_error",
"rustc_trait_selection::error_reporting::traits::fulfillment_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
::tracing_core::__macro_support::Option::Some(1587u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::fulfillment_errors"),
::tracing_core::field::FieldSet::new(&[],
::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,
&{ meta.fields().value_set(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ErrorGuaranteed = loop {};
return __tracing_attr_fake_return;
}
{
let predicate =
self.resolve_vars_if_possible(obligation.predicate);
if let Err(e) = predicate.error_reported() { return e; }
self.probe(|_|
{
let bound_predicate = predicate.kind();
let (values, err) =
match bound_predicate.skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Projection(data))
=> {
let ocx = ObligationCtxt::new(self);
let data =
self.instantiate_binder_with_fresh_vars(obligation.cause.span,
infer::BoundRegionConversionTime::HigherRankedType,
bound_predicate.rebind(data));
let unnormalized_term =
data.projection_term.to_term(self.tcx, ty::IsRigid::No);
let normalized_term =
ocx.normalize(&obligation.cause, obligation.param_env,
Unnormalized::new_wip(unnormalized_term));
let _ = ocx.try_evaluate_obligations();
if let Err(new_err) =
ocx.eq(&obligation.cause, obligation.param_env, data.term,
normalized_term) {
(Some((data.projection_term,
self.resolve_vars_if_possible(normalized_term), data.term)),
new_err)
} else { (None, error.err) }
}
_ => (None, error.err),
};
let mut file = None;
let (msg, span, closure_span) =
values.and_then(|(predicate, normalized_term,
expected_term)|
{
self.maybe_detailed_projection_msg(obligation.cause.span,
predicate, normalized_term, expected_term, &mut file)
}).unwrap_or_else(||
{
({
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type mismatch resolving `{0}`",
self.tcx.short_string(self.resolve_vars_if_possible(predicate),
&mut file)))
})
}, obligation.cause.span, None)
});
let mut diag =
{
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", msg))
})).with_code(E0271)
};
*diag.long_ty_path() = file;
if let Some(span) = closure_span {
diag.span_label(span, "this closure");
if !span.overlaps(obligation.cause.span) {
diag.span_label(obligation.cause.span, "closure used here");
}
}
let secondary_span =
self.probe(|_|
{
let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
predicate.kind().skip_binder() else { return None; };
if !proj.projection_term.kind.is_trait_projection() {
return None;
}
let trait_ref =
self.enter_forall_and_leak_universe(predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)));
let Ok(Some(ImplSource::UserDefined(impl_data))) =
SelectionContext::new(self).select(&obligation.with(self.tcx,
trait_ref)) else { return None; };
let Ok(node) =
specialization_graph::assoc_def(self.tcx,
impl_data.impl_def_id, proj.def_id()) else { return None; };
if !node.is_final() { return None; }
match self.tcx.hir_get_if_local(node.item.def_id) {
Some(hir::Node::TraitItem(hir::TraitItem {
kind: hir::TraitItemKind::Type(_, Some(ty)), .. }) |
hir::Node::ImplItem(hir::ImplItem {
kind: hir::ImplItemKind::Type(ty), .. })) =>
Some((ty.span,
{
let _guard = ForceTrimmedGuard::new();
Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type mismatch resolving `{0}`",
self.tcx.short_string(self.resolve_vars_if_possible(predicate),
diag.long_ty_path())))
}))
}, true)),
_ => None,
}
});
self.note_type_err(&mut diag, &obligation.cause,
secondary_span,
values.map(|(_, normalized_ty, expected_ty)|
{
obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(expected_ty,
normalized_ty)))
}), err, false, Some(span));
self.note_obligation_cause(&mut diag, obligation);
diag.emit()
})
}
}
}#[instrument(level = "debug", skip_all)]
1588 pub(super) fn report_projection_error(
1589 &self,
1590 obligation: &PredicateObligation<'tcx>,
1591 error: &MismatchedProjectionTypes<'tcx>,
1592 ) -> ErrorGuaranteed {
1593 let predicate = self.resolve_vars_if_possible(obligation.predicate);
1594
1595 if let Err(e) = predicate.error_reported() {
1596 return e;
1597 }
1598
1599 self.probe(|_| {
1600 let bound_predicate = predicate.kind();
1605 let (values, err) = match bound_predicate.skip_binder() {
1606 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
1607 let ocx = ObligationCtxt::new(self);
1608
1609 let data = self.instantiate_binder_with_fresh_vars(
1610 obligation.cause.span,
1611 infer::BoundRegionConversionTime::HigherRankedType,
1612 bound_predicate.rebind(data),
1613 );
1614 let unnormalized_term = data.projection_term.to_term(self.tcx, ty::IsRigid::No);
1615 let normalized_term = ocx.normalize(
1618 &obligation.cause,
1619 obligation.param_env,
1620 Unnormalized::new_wip(unnormalized_term),
1621 );
1622
1623 let _ = ocx.try_evaluate_obligations();
1629
1630 if let Err(new_err) =
1631 ocx.eq(&obligation.cause, obligation.param_env, data.term, normalized_term)
1632 {
1633 (
1634 Some((
1635 data.projection_term,
1636 self.resolve_vars_if_possible(normalized_term),
1637 data.term,
1638 )),
1639 new_err,
1640 )
1641 } else {
1642 (None, error.err)
1643 }
1644 }
1645 _ => (None, error.err),
1646 };
1647
1648 let mut file = None;
1649 let (msg, span, closure_span) = values
1650 .and_then(|(predicate, normalized_term, expected_term)| {
1651 self.maybe_detailed_projection_msg(
1652 obligation.cause.span,
1653 predicate,
1654 normalized_term,
1655 expected_term,
1656 &mut file,
1657 )
1658 })
1659 .unwrap_or_else(|| {
1660 (
1661 with_forced_trimmed_paths!(format!(
1662 "type mismatch resolving `{}`",
1663 self.tcx
1664 .short_string(self.resolve_vars_if_possible(predicate), &mut file),
1665 )),
1666 obligation.cause.span,
1667 None,
1668 )
1669 });
1670 let mut diag = struct_span_code_err!(self.dcx(), span, E0271, "{msg}");
1671 *diag.long_ty_path() = file;
1672 if let Some(span) = closure_span {
1673 diag.span_label(span, "this closure");
1690 if !span.overlaps(obligation.cause.span) {
1691 diag.span_label(obligation.cause.span, "closure used here");
1693 }
1694 }
1695
1696 let secondary_span = self.probe(|_| {
1697 let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1698 predicate.kind().skip_binder()
1699 else {
1700 return None;
1701 };
1702 if !proj.projection_term.kind.is_trait_projection() {
1703 return None;
1704 }
1705
1706 let trait_ref = self.enter_forall_and_leak_universe(
1707 predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)),
1708 );
1709 let Ok(Some(ImplSource::UserDefined(impl_data))) =
1710 SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref))
1711 else {
1712 return None;
1713 };
1714
1715 let Ok(node) =
1716 specialization_graph::assoc_def(self.tcx, impl_data.impl_def_id, proj.def_id())
1717 else {
1718 return None;
1719 };
1720
1721 if !node.is_final() {
1722 return None;
1723 }
1724
1725 match self.tcx.hir_get_if_local(node.item.def_id) {
1726 Some(
1727 hir::Node::TraitItem(hir::TraitItem {
1728 kind: hir::TraitItemKind::Type(_, Some(ty)),
1729 ..
1730 })
1731 | hir::Node::ImplItem(hir::ImplItem {
1732 kind: hir::ImplItemKind::Type(ty),
1733 ..
1734 }),
1735 ) => Some((
1736 ty.span,
1737 with_forced_trimmed_paths!(Cow::from(format!(
1738 "type mismatch resolving `{}`",
1739 self.tcx.short_string(
1740 self.resolve_vars_if_possible(predicate),
1741 diag.long_ty_path()
1742 ),
1743 ))),
1744 true,
1745 )),
1746 _ => None,
1747 }
1748 });
1749
1750 self.note_type_err(
1751 &mut diag,
1752 &obligation.cause,
1753 secondary_span,
1754 values.map(|(_, normalized_ty, expected_ty)| {
1755 obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(
1756 expected_ty,
1757 normalized_ty,
1758 )))
1759 }),
1760 err,
1761 false,
1762 Some(span),
1763 );
1764 self.note_obligation_cause(&mut diag, obligation);
1765 diag.emit()
1766 })
1767 }
1768
1769 fn maybe_detailed_projection_msg(
1770 &self,
1771 mut span: Span,
1772 projection_term: ty::AliasTerm<'tcx>,
1773 normalized_ty: ty::Term<'tcx>,
1774 expected_ty: ty::Term<'tcx>,
1775 long_ty_path: &mut Option<PathBuf>,
1776 ) -> Option<(String, Span, Option<Span>)> {
1777 if !projection_term.kind.is_trait_projection() {
1778 return None;
1779 }
1780
1781 let projection_def_id = projection_term.expect_projection_def_id();
1782 let trait_def_id = projection_term.trait_def_id(self.tcx);
1783 let self_ty = projection_term.self_ty();
1784
1785 {
let _guard = ForceTrimmedGuard::new();
if self.tcx.is_lang_item(projection_def_id, LangItem::FnOnceOutput) {
let (span, closure_span) =
if let ty::Closure(def_id, _) = *self_ty.kind() {
let def_span = self.tcx.def_span(def_id);
if let Some(local_def_id) = def_id.as_local() &&
let node = self.tcx.hir_node_by_def_id(local_def_id) &&
let Some(fn_decl) = node.fn_decl() &&
let Some(id) = node.body_id() {
span =
match fn_decl.output {
hir::FnRetTy::Return(ty) => ty.span,
hir::FnRetTy::DefaultReturn(_) => {
let body = self.tcx.hir_body(id);
match body.value.kind {
hir::ExprKind::Block(hir::Block { expr: Some(expr), .. }, _)
=> expr.span,
hir::ExprKind::Block(hir::Block {
expr: None, stmts: [.., last], .. }, _) => last.span,
_ => body.value.span,
}
}
};
}
(span, Some(def_span))
} else { (span, None) };
let item =
match self_ty.kind() {
ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
_ => self.tcx.short_string(self_ty, long_ty_path),
};
let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
let normalized_ty =
self.tcx.short_string(normalized_ty, long_ty_path);
Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` to return `{1}`, but it returns `{2}`",
item, expected_ty, normalized_ty))
}), span, closure_span))
} else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
let self_ty = self.tcx.short_string(self_ty, long_ty_path);
let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
let normalized_ty =
self.tcx.short_string(normalized_ty, long_ty_path);
Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` to be a future that resolves to `{1}`, but it resolves to `{2}`",
self_ty, expected_ty, normalized_ty))
}), span, None))
} else if Some(trait_def_id) ==
self.tcx.get_diagnostic_item(sym::Iterator) {
let self_ty = self.tcx.short_string(self_ty, long_ty_path);
let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
let normalized_ty =
self.tcx.short_string(normalized_ty, long_ty_path);
Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` to be an iterator that yields `{1}`, but it yields `{2}`",
self_ty, expected_ty, normalized_ty))
}), span, None))
} else { None }
}with_forced_trimmed_paths! {
1786 if self.tcx.is_lang_item(projection_def_id, LangItem::FnOnceOutput) {
1787 let (span, closure_span) = if let ty::Closure(def_id, _) = *self_ty.kind() {
1788 let def_span = self.tcx.def_span(def_id);
1789 if let Some(local_def_id) = def_id.as_local()
1790 && let node = self.tcx.hir_node_by_def_id(local_def_id)
1791 && let Some(fn_decl) = node.fn_decl()
1792 && let Some(id) = node.body_id()
1793 {
1794 span = match fn_decl.output {
1795 hir::FnRetTy::Return(ty) => ty.span,
1796 hir::FnRetTy::DefaultReturn(_) => {
1797 let body = self.tcx.hir_body(id);
1798 match body.value.kind {
1799 hir::ExprKind::Block(
1800 hir::Block { expr: Some(expr), .. },
1801 _,
1802 ) => expr.span,
1803 hir::ExprKind::Block(
1804 hir::Block {
1805 expr: None, stmts: [.., last], ..
1806 },
1807 _,
1808 ) => last.span,
1809 _ => body.value.span,
1810 }
1811 }
1812 };
1813 }
1814 (span, Some(def_span))
1815 } else {
1816 (span, None)
1817 };
1818 let item = match self_ty.kind() {
1819 ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
1820 _ => self.tcx.short_string(self_ty, long_ty_path),
1821 };
1822 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1823 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1824 Some((format!(
1825 "expected `{item}` to return `{expected_ty}`, but it returns `{normalized_ty}`",
1826 ), span, closure_span))
1827 } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
1828 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1829 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1830 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1831 Some((format!(
1832 "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
1833 resolves to `{normalized_ty}`"
1834 ), span, None))
1835 } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
1836 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1837 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1838 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1839 Some((format!(
1840 "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
1841 yields `{normalized_ty}`"
1842 ), span, None))
1843 } else {
1844 None
1845 }
1846 }
1847 }
1848
1849 pub fn fuzzy_match_tys(
1850 &self,
1851 mut a: Ty<'tcx>,
1852 mut b: Ty<'tcx>,
1853 ignoring_lifetimes: bool,
1854 ) -> Option<CandidateSimilarity> {
1855 fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
1858 match t.kind() {
1859 ty::Bool => Some(0),
1860 ty::Char => Some(1),
1861 ty::Str => Some(2),
1862 ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => Some(2),
1863 ty::Int(..)
1864 | ty::Uint(..)
1865 | ty::Float(..)
1866 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
1867 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1868 ty::Array(..) | ty::Slice(..) => Some(6),
1869 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1870 ty::Dynamic(..) => Some(8),
1871 ty::Closure(..) => Some(9),
1872 ty::Tuple(..) => Some(10),
1873 ty::Param(..) => Some(11),
1874 ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. }, .. }) => Some(12),
1875 ty::Alias(_, ty::AliasTy { kind: ty::Inherent { .. }, .. }) => Some(13),
1876 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => Some(14),
1877 ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) => Some(15),
1878 ty::Never => Some(16),
1879 ty::Adt(..) => Some(17),
1880 ty::Coroutine(..) => Some(18),
1881 ty::Foreign(..) => Some(19),
1882 ty::CoroutineWitness(..) => Some(20),
1883 ty::CoroutineClosure(..) => Some(21),
1884 ty::Pat(..) => Some(22),
1885 ty::UnsafeBinder(..) => Some(23),
1886 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1887 }
1888 }
1889
1890 let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
1891 loop {
1892 match t.kind() {
1893 ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => t = *inner,
1894 _ => break t,
1895 }
1896 }
1897 };
1898
1899 if !ignoring_lifetimes {
1900 a = strip_references(a);
1901 b = strip_references(b);
1902 }
1903
1904 let cat_a = type_category(self.tcx, a)?;
1905 let cat_b = type_category(self.tcx, b)?;
1906 if a == b {
1907 Some(CandidateSimilarity::Exact { ignoring_lifetimes })
1908 } else if cat_a == cat_b {
1909 match (a.kind(), b.kind()) {
1910 (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
1911 (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
1912 (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
1918 self.fuzzy_match_tys(a, b, true).is_some()
1919 }
1920 _ => true,
1921 }
1922 .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
1923 } else if ignoring_lifetimes {
1924 None
1925 } else {
1926 self.fuzzy_match_tys(a, b, true)
1927 }
1928 }
1929
1930 pub(super) fn describe_closure(&self, kind: hir::ClosureKind) -> &'static str {
1931 match kind {
1932 hir::ClosureKind::Closure => "a closure",
1933 hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => "a coroutine",
1934 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1935 hir::CoroutineDesugaring::Async,
1936 hir::CoroutineSource::Block,
1937 )) => "an async block",
1938 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1939 hir::CoroutineDesugaring::Async,
1940 hir::CoroutineSource::Fn,
1941 )) => "an async function",
1942 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1943 hir::CoroutineDesugaring::Async,
1944 hir::CoroutineSource::Closure,
1945 ))
1946 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
1947 "an async closure"
1948 }
1949 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1950 hir::CoroutineDesugaring::AsyncGen,
1951 hir::CoroutineSource::Block,
1952 )) => "an async gen block",
1953 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1954 hir::CoroutineDesugaring::AsyncGen,
1955 hir::CoroutineSource::Fn,
1956 )) => "an async gen function",
1957 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1958 hir::CoroutineDesugaring::AsyncGen,
1959 hir::CoroutineSource::Closure,
1960 ))
1961 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
1962 "an async gen closure"
1963 }
1964 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1965 hir::CoroutineDesugaring::Gen,
1966 hir::CoroutineSource::Block,
1967 )) => "a gen block",
1968 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1969 hir::CoroutineDesugaring::Gen,
1970 hir::CoroutineSource::Fn,
1971 )) => "a gen function",
1972 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1973 hir::CoroutineDesugaring::Gen,
1974 hir::CoroutineSource::Closure,
1975 ))
1976 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => "a gen closure",
1977 }
1978 }
1979
1980 pub(super) fn find_similar_impl_candidates(
1981 &self,
1982 trait_pred: ty::PolyTraitPredicate<'tcx>,
1983 ) -> Vec<ImplCandidate<'tcx>> {
1984 let mut candidates: Vec<_> = self
1985 .tcx
1986 .all_impls(trait_pred.def_id())
1987 .filter_map(|def_id| {
1988 let imp = self.tcx.impl_trait_header(def_id);
1989 if imp.polarity != ty::ImplPolarity::Positive
1990 || !self.tcx.is_user_visible_dep(def_id.krate)
1991 {
1992 return None;
1993 }
1994 let imp = imp.trait_ref.skip_binder();
1995
1996 self.fuzzy_match_tys(trait_pred.skip_binder().self_ty(), imp.self_ty(), false).map(
1997 |similarity| ImplCandidate { trait_ref: imp, similarity, impl_def_id: def_id },
1998 )
1999 })
2000 .collect();
2001 if candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
2002 candidates.retain(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. }));
2006 }
2007 candidates
2008 }
2009
2010 pub(super) fn report_similar_impl_candidates(
2011 &self,
2012 impl_candidates: &[ImplCandidate<'tcx>],
2013 obligation: &PredicateObligation<'tcx>,
2014 trait_pred: ty::PolyTraitPredicate<'tcx>,
2015 body_def_id: LocalDefId,
2016 err: &mut Diag<'_>,
2017 other: bool,
2018 param_env: ty::ParamEnv<'tcx>,
2019 ) -> bool {
2020 let parent_map = self.tcx.visible_parent_map(());
2021 let alternative_candidates = |def_id: DefId| {
2022 let mut impl_candidates: Vec<_> = self
2023 .tcx
2024 .all_impls(def_id)
2025 .filter(|def_id| !self.tcx.do_not_recommend_impl(*def_id))
2027 .map(|def_id| (self.tcx.impl_trait_header(def_id), def_id))
2029 .filter_map(|(header, def_id)| {
2030 (header.polarity == ty::ImplPolarity::Positive
2031 || self.tcx.is_automatically_derived(def_id))
2032 .then(|| (header.trait_ref.instantiate_identity().skip_norm_wip(), def_id))
2033 })
2034 .filter(|(trait_ref, _)| {
2035 let self_ty = trait_ref.self_ty();
2036 if let ty::Param(_) = self_ty.kind() {
2038 false
2039 }
2040 else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
2042 let mut did = def.did();
2046 if self.tcx.visibility(did).is_accessible_from(body_def_id, self.tcx) {
2047 if !did.is_local() {
2049 let mut previously_seen_dids: FxHashSet<DefId> = Default::default();
2050 previously_seen_dids.insert(did);
2051 while let Some(&parent) = parent_map.get(&did)
2052 && let hash_set::Entry::Vacant(v) =
2053 previously_seen_dids.entry(parent)
2054 {
2055 if self.tcx.is_doc_hidden(did) {
2056 return false;
2057 }
2058 v.insert();
2059 did = parent;
2060 }
2061 }
2062 true
2063 } else {
2064 false
2065 }
2066 } else {
2067 true
2068 }
2069 })
2070 .collect();
2071
2072 impl_candidates.sort_by_key(|(tr, _)| tr.to_string());
2073 impl_candidates.dedup();
2074 impl_candidates
2075 };
2076
2077 if let [single] = &impl_candidates {
2078 let self_ty = trait_pred.skip_binder().self_ty();
2079 if !self_ty.has_escaping_bound_vars() {
2080 let self_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
2081 if let ty::Ref(_, inner_ty, _) = self_ty.kind()
2082 && self.can_eq(param_env, single.trait_ref.self_ty(), *inner_ty)
2083 && !self.where_clause_expr_matches_failed_self_ty(obligation, self_ty)
2084 {
2085 return true;
2089 }
2090 }
2091
2092 if self.probe(|_| {
2095 let ocx = ObligationCtxt::new(self);
2096
2097 self.enter_forall(trait_pred, |obligation_trait_ref| {
2098 let impl_args = self.fresh_args_for_item(DUMMY_SP, single.impl_def_id);
2099 let impl_trait_ref = ocx.normalize(
2100 &ObligationCause::dummy(),
2101 param_env,
2102 ty::EarlyBinder::bind(self.tcx, single.trait_ref)
2103 .instantiate(self.tcx, impl_args),
2104 );
2105
2106 ocx.register_obligations(
2107 self.tcx
2108 .predicates_of(single.impl_def_id)
2109 .instantiate(self.tcx, impl_args)
2110 .into_iter()
2111 .map(|(clause, _)| {
2112 Obligation::new(
2113 self.tcx,
2114 ObligationCause::dummy(),
2115 param_env,
2116 clause.skip_norm_wip(),
2117 )
2118 }),
2119 );
2120 if !ocx.try_evaluate_obligations().is_empty() {
2121 return false;
2122 }
2123
2124 let mut terrs = ::alloc::vec::Vec::new()vec![];
2125 for (obligation_arg, impl_arg) in
2126 std::iter::zip(obligation_trait_ref.trait_ref.args, impl_trait_ref.args)
2127 {
2128 if (obligation_arg, impl_arg).references_error() {
2129 return false;
2130 }
2131 if let Err(terr) =
2132 ocx.eq(&ObligationCause::dummy(), param_env, impl_arg, obligation_arg)
2133 {
2134 terrs.push(terr);
2135 }
2136 if !ocx.try_evaluate_obligations().is_empty() {
2137 return false;
2138 }
2139 }
2140
2141 if terrs.len() == impl_trait_ref.args.len() {
2143 return false;
2144 }
2145
2146 let impl_trait_ref = self.resolve_vars_if_possible(impl_trait_ref);
2147 if impl_trait_ref.references_error() {
2148 return false;
2149 }
2150
2151 if let [child, ..] = &err.children[..]
2152 && child.level == Level::Help
2153 && let Some(line) = child.messages.get(0)
2154 && let Some(line) = line.0.as_str()
2155 && line.starts_with("the trait")
2156 && line.contains("is not implemented for")
2157 {
2158 err.children.remove(0);
2165 }
2166
2167 let traits = self.cmp_traits(
2168 obligation_trait_ref.def_id(),
2169 &obligation_trait_ref.trait_ref.args[1..],
2170 impl_trait_ref.def_id,
2171 &impl_trait_ref.args[1..],
2172 );
2173 let traits_content = (traits.0.content(), traits.1.content());
2174 let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty());
2175 let types_content = (types.0.content(), types.1.content());
2176 let mut msg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal("the trait `")]))vec![StringPart::normal("the trait `")];
2177 if traits_content.0 == traits_content.1 {
2178 msg.push(StringPart::normal(
2179 impl_trait_ref.print_trait_sugared().to_string(),
2180 ));
2181 } else {
2182 msg.extend(traits.0.0);
2183 }
2184 msg.extend([
2185 StringPart::normal("` "),
2186 StringPart::highlighted("is not"),
2187 StringPart::normal(" implemented for `"),
2188 ]);
2189 if types_content.0 == types_content.1 {
2190 let ty = self
2191 .tcx
2192 .short_string(obligation_trait_ref.self_ty(), err.long_ty_path());
2193 msg.push(StringPart::normal(ty));
2194 } else {
2195 msg.extend(types.0.0);
2196 }
2197 msg.push(StringPart::normal("`"));
2198 if types_content.0 == types_content.1 {
2199 msg.push(StringPart::normal("\nbut trait `"));
2200 msg.extend(traits.1.0);
2201 msg.extend([
2202 StringPart::normal("` "),
2203 StringPart::highlighted("is"),
2204 StringPart::normal(" implemented for it"),
2205 ]);
2206 } else if traits_content.0 == traits_content.1 {
2207 msg.extend([
2208 StringPart::normal("\nbut it "),
2209 StringPart::highlighted("is"),
2210 StringPart::normal(" implemented for `"),
2211 ]);
2212 msg.extend(types.1.0);
2213 msg.push(StringPart::normal("`"));
2214 } else {
2215 msg.push(StringPart::normal("\nbut trait `"));
2216 msg.extend(traits.1.0);
2217 msg.extend([
2218 StringPart::normal("` "),
2219 StringPart::highlighted("is"),
2220 StringPart::normal(" implemented for `"),
2221 ]);
2222 msg.extend(types.1.0);
2223 msg.push(StringPart::normal("`"));
2224 }
2225 err.highlighted_span_help(self.tcx.def_span(single.impl_def_id), msg);
2226
2227 if let [TypeError::Sorts(exp_found)] = &terrs[..] {
2228 let exp_found = self.resolve_vars_if_possible(*exp_found);
2229 let expected =
2230 self.tcx.short_string(exp_found.expected, err.long_ty_path());
2231 let found = self.tcx.short_string(exp_found.found, err.long_ty_path());
2232 err.highlighted_help(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal("for that trait implementation, "),
StringPart::normal("expected `"),
StringPart::highlighted(expected),
StringPart::normal("`, found `"),
StringPart::highlighted(found), StringPart::normal("`")]))vec![
2233 StringPart::normal("for that trait implementation, "),
2234 StringPart::normal("expected `"),
2235 StringPart::highlighted(expected),
2236 StringPart::normal("`, found `"),
2237 StringPart::highlighted(found),
2238 StringPart::normal("`"),
2239 ]);
2240 self.suggest_function_pointers_impl(None, &exp_found, err);
2241 }
2242
2243 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2244 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2245 && !crates.is_empty()
2246 {
2247 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2248 err.help("you can use `cargo tree` to explore your dependency tree");
2249 }
2250 true
2251 })
2252 }) {
2253 return true;
2254 }
2255 }
2256
2257 let other = if other { "other " } else { "" };
2258 let report = |mut candidates: Vec<(TraitRef<'tcx>, DefId)>, err: &mut Diag<'_>| {
2259 candidates.retain(|(tr, _)| !tr.references_error());
2260 if candidates.is_empty() {
2261 return false;
2262 }
2263 let mut specific_candidates = candidates.clone();
2264 specific_candidates.retain(|(tr, _)| {
2265 tr.with_replaced_self_ty(self.tcx, trait_pred.skip_binder().self_ty())
2266 == trait_pred.skip_binder().trait_ref
2267 });
2268 if !specific_candidates.is_empty() {
2269 candidates = specific_candidates;
2272 }
2273 if let &[(cand, def_id)] = &candidates[..] {
2274 if self.tcx.is_diagnostic_item(sym::FromResidual, cand.def_id)
2275 && !self.tcx.features().enabled(sym::try_trait_v2)
2276 {
2277 return false;
2278 }
2279 let mut multi_span = MultiSpan::from_span(self.tcx.def_span(def_id));
2280 let (desc, mention_castable) =
2281 match (cand.self_ty().kind(), trait_pred.self_ty().skip_binder().kind()) {
2282 (ty::FnPtr(..), ty::FnDef(..)) => {
2283 (" implemented for fn pointer `", ", cast using `as`")
2284 }
2285 (ty::FnPtr(..), _) => (" implemented for fn pointer `", ""),
2286 _ => {
2287 let evaluate_obligations = || {
2288 let ocx = ObligationCtxt::new_with_diagnostics(self);
2289 self.enter_forall(trait_pred, |obligation_trait_ref| {
2290 let impl_args = self.fresh_args_for_item(DUMMY_SP, def_id);
2291 let impl_trait_ref = ocx.normalize(
2292 &ObligationCause::dummy(),
2293 param_env,
2294 ty::EarlyBinder::bind(self.tcx, cand)
2295 .instantiate(self.tcx, impl_args),
2296 );
2297 if ocx
2298 .eq(
2299 &ObligationCause::dummy(),
2300 param_env,
2301 obligation_trait_ref.trait_ref,
2302 impl_trait_ref,
2303 )
2304 .is_err()
2305 {
2306 return Vec::new();
2307 }
2308 ocx.register_obligations(
2309 self.tcx
2310 .predicates_of(def_id)
2311 .instantiate(self.tcx, impl_args)
2312 .into_iter()
2313 .map(|(clause, span)| {
2314 Obligation::new(
2315 self.tcx,
2316 ObligationCause::dummy_with_span(span),
2317 param_env,
2318 clause.skip_normalization(),
2319 )
2320 }),
2321 );
2322 ocx.try_evaluate_obligations()
2323 })
2324 };
2325 let failing_obligations =
2326 if !self.tcx.predicates_of(def_id).predicates.is_empty() {
2327 self.probe(|_| evaluate_obligations())
2328 } else {
2329 Vec::new()
2330 };
2331
2332 if failing_obligations.is_empty() {
2333 (" implemented for `", "")
2334 } else {
2335 for error in failing_obligations {
2336 multi_span.push_span_label(
2337 error.root_obligation.cause.span,
2338 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied requirement introduced here: `{0}`",
error.root_obligation.predicate))
})format!(
2339 "unsatisfied requirement introduced here: `{}`",
2340 error.root_obligation.predicate,
2341 ),
2342 );
2343 }
2344
2345 (" conditionally implemented for `", "")
2346 }
2347 }
2348 };
2349 let trait_ = self.tcx.short_string(cand.print_trait_sugared(), err.long_ty_path());
2350 let self_ty = self.tcx.short_string(cand.self_ty(), err.long_ty_path());
2351 err.highlighted_span_help(
2352 multi_span,
2353 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait `{0}` ",
trait_))
})), StringPart::highlighted("is"),
StringPart::normal(desc), StringPart::highlighted(self_ty),
StringPart::normal("`"),
StringPart::normal(mention_castable)]))vec![
2354 StringPart::normal(format!("the trait `{trait_}` ")),
2355 StringPart::highlighted("is"),
2356 StringPart::normal(desc),
2357 StringPart::highlighted(self_ty),
2358 StringPart::normal("`"),
2359 StringPart::normal(mention_castable),
2360 ],
2361 );
2362 return true;
2363 }
2364 let trait_ref = TraitRef::identity(self.tcx, candidates[0].0.def_id);
2365 let mut traits: Vec<_> =
2367 candidates.iter().map(|(c, _)| c.print_only_trait_path().to_string()).collect();
2368 traits.sort();
2369 traits.dedup();
2370 let all_traits_equal = traits.len() == 1;
2373 let mut types: Vec<_> =
2374 candidates.iter().map(|(c, _)| c.self_ty().to_string()).collect();
2375 types.sort();
2376 types.dedup();
2377 let all_types_equal = types.len() == 1;
2378
2379 let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose {
2380 candidates.len()
2381 } else {
2382 8
2383 };
2384 if candidates.len() < 5 {
2385 let spans: Vec<_> =
2386 candidates.iter().map(|&(_, def_id)| self.tcx.def_span(def_id)).collect();
2387 let mut span: MultiSpan = spans.into();
2388 for (c, def_id) in &candidates {
2389 let msg = if all_traits_equal {
2390 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.short_string(c.self_ty(), err.long_ty_path())))
})format!("`{}`", self.tcx.short_string(c.self_ty(), err.long_ty_path()))
2391 } else if all_types_equal {
2392 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2393 "`{}`",
2394 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path())
2395 )
2396 } else {
2397 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements `{1}`",
self.tcx.short_string(c.self_ty(), err.long_ty_path()),
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2398 "`{}` implements `{}`",
2399 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2400 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path()),
2401 )
2402 };
2403 span.push_span_label(self.tcx.def_span(*def_id), msg);
2404 }
2405 let msg = if all_types_equal {
2406 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements trait `{1}`",
self.tcx.short_string(candidates[0].0.self_ty(),
err.long_ty_path()),
self.tcx.short_string(trait_ref.print_trait_sugared(),
err.long_ty_path())))
})format!(
2407 "`{}` implements trait `{}`",
2408 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2409 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2410 )
2411 } else {
2412 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following {1}types implement trait `{0}`",
self.tcx.short_string(trait_ref.print_trait_sugared(),
err.long_ty_path()), other))
})format!(
2413 "the following {other}types implement trait `{}`",
2414 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2415 )
2416 };
2417 err.span_help(span, msg);
2418 } else {
2419 let candidate_names: Vec<String> = candidates
2420 .iter()
2421 .map(|(c, _)| {
2422 if all_traits_equal {
2423 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n {0}",
self.tcx.short_string(c.self_ty(), err.long_ty_path())))
})format!(
2424 "\n {}",
2425 self.tcx.short_string(c.self_ty(), err.long_ty_path())
2426 )
2427 } else if all_types_equal {
2428 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n {0}",
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2429 "\n {}",
2430 self.tcx
2431 .short_string(c.print_only_trait_path(), err.long_ty_path())
2432 )
2433 } else {
2434 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n `{0}` implements `{1}`",
self.tcx.short_string(c.self_ty(), err.long_ty_path()),
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2435 "\n `{}` implements `{}`",
2436 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2437 self.tcx
2438 .short_string(c.print_only_trait_path(), err.long_ty_path()),
2439 )
2440 }
2441 })
2442 .collect();
2443 let msg = if all_types_equal {
2444 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements trait `{1}`",
self.tcx.short_string(candidates[0].0.self_ty(),
err.long_ty_path()),
self.tcx.short_string(trait_ref.print_trait_sugared(),
err.long_ty_path())))
})format!(
2445 "`{}` implements trait `{}`",
2446 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2447 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2448 )
2449 } else {
2450 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following {1}types implement trait `{0}`",
self.tcx.short_string(trait_ref.print_trait_sugared(),
err.long_ty_path()), other))
})format!(
2451 "the following {other}types implement trait `{}`",
2452 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2453 )
2454 };
2455
2456 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2}:{0}{1}",
candidate_names[..end].join(""),
if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} others",
candidates.len() - 8))
})
} else { String::new() }, msg))
})format!(
2457 "{msg}:{}{}",
2458 candidate_names[..end].join(""),
2459 if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
2460 format!("\nand {} others", candidates.len() - 8)
2461 } else {
2462 String::new()
2463 }
2464 ));
2465 }
2466
2467 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2468 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2469 && !crates.is_empty()
2470 {
2471 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2472 err.help("you can use `cargo tree` to explore your dependency tree");
2473 }
2474 true
2475 };
2476
2477 let impl_candidates = impl_candidates
2480 .into_iter()
2481 .cloned()
2482 .filter(|cand| !self.tcx.do_not_recommend_impl(cand.impl_def_id))
2483 .collect::<Vec<_>>();
2484
2485 let def_id = trait_pred.def_id();
2486 if impl_candidates.is_empty() {
2487 if self.tcx.trait_is_auto(def_id)
2488 || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2489 || self.tcx.get_diagnostic_name(def_id).is_some()
2490 {
2491 return false;
2493 }
2494 return report(alternative_candidates(def_id), err);
2495 }
2496
2497 let mut impl_candidates: Vec<_> = impl_candidates
2504 .iter()
2505 .cloned()
2506 .filter(|cand| !cand.trait_ref.references_error())
2507 .map(|mut cand| {
2508 cand.trait_ref = self
2512 .tcx
2513 .try_normalize_erasing_regions(
2514 ty::TypingEnv::non_body_analysis(self.tcx, cand.impl_def_id),
2515 Unnormalized::new_wip(cand.trait_ref),
2516 )
2517 .unwrap_or(cand.trait_ref);
2518 cand
2519 })
2520 .collect();
2521 impl_candidates.sort_by_key(|cand| {
2522 let len = if let GenericArgKind::Type(ty) = cand.trait_ref.args[0].kind()
2524 && let ty::Array(_, len) = ty.kind()
2525 {
2526 len.try_to_target_usize(self.tcx).unwrap_or(u64::MAX)
2528 } else {
2529 0
2530 };
2531
2532 (cand.similarity, len, cand.trait_ref.to_string())
2533 });
2534 let mut impl_candidates: Vec<_> =
2535 impl_candidates.into_iter().map(|cand| (cand.trait_ref, cand.impl_def_id)).collect();
2536 impl_candidates.dedup();
2537
2538 report(impl_candidates, err)
2539 }
2540
2541 fn report_similar_impl_candidates_for_root_obligation(
2542 &self,
2543 obligation: &PredicateObligation<'tcx>,
2544 trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2545 body_def_id: LocalDefId,
2546 err: &mut Diag<'_>,
2547 ) {
2548 let mut code = obligation.cause.code();
2555 let mut trait_pred = trait_predicate;
2556 let mut peeled = false;
2557 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
2558 code = parent_code;
2559 if let Some(parent_trait_pred) = parent_trait_pred {
2560 trait_pred = parent_trait_pred;
2561 peeled = true;
2562 }
2563 }
2564 let def_id = trait_pred.def_id();
2565 if peeled && !self.tcx.trait_is_auto(def_id) && self.tcx.as_lang_item(def_id).is_none() {
2571 let impl_candidates = self.find_similar_impl_candidates(trait_pred);
2572 self.report_similar_impl_candidates(
2573 &impl_candidates,
2574 obligation,
2575 trait_pred,
2576 body_def_id,
2577 err,
2578 true,
2579 obligation.param_env,
2580 );
2581 }
2582 }
2583
2584 fn get_parent_trait_ref(
2586 &self,
2587 code: &ObligationCauseCode<'tcx>,
2588 ) -> Option<(Ty<'tcx>, Option<Span>)> {
2589 match code {
2590 ObligationCauseCode::BuiltinDerived(data) => {
2591 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2592 match self.get_parent_trait_ref(&data.parent_code) {
2593 Some(t) => Some(t),
2594 None => {
2595 let ty = parent_trait_ref.skip_binder().self_ty();
2596 let span = TyCategory::from_ty(self.tcx, ty)
2597 .map(|(_, def_id)| self.tcx.def_span(def_id));
2598 Some((ty, span))
2599 }
2600 }
2601 }
2602 ObligationCauseCode::FunctionArg { parent_code, .. } => {
2603 self.get_parent_trait_ref(parent_code)
2604 }
2605 _ => None,
2606 }
2607 }
2608
2609 fn check_same_trait_different_version(
2610 &self,
2611 err: &mut Diag<'_>,
2612 trait_pred: ty::PolyTraitPredicate<'tcx>,
2613 ) -> bool {
2614 let get_trait_impls = |trait_def_id| {
2615 let mut trait_impls = ::alloc::vec::Vec::new()vec![];
2616 self.tcx.for_each_relevant_impl(
2617 trait_def_id,
2618 trait_pred.skip_binder().self_ty(),
2619 |impl_def_id| {
2620 let impl_trait_header = self.tcx.impl_trait_header(impl_def_id);
2621 trait_impls
2622 .push(self.tcx.def_span(impl_trait_header.trait_ref.skip_binder().def_id));
2623 },
2624 );
2625 trait_impls
2626 };
2627 self.check_same_definition_different_crate(
2628 err,
2629 trait_pred.def_id(),
2630 self.tcx.visible_traits(),
2631 get_trait_impls,
2632 "trait",
2633 )
2634 }
2635
2636 pub fn note_two_crate_versions(
2637 &self,
2638 krate: CrateNum,
2639 sp: impl Into<MultiSpan>,
2640 err: &mut Diag<'_>,
2641 ) {
2642 let crate_name = self.tcx.crate_name(krate);
2643 let crate_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("there are multiple different versions of crate `{0}` in the dependency graph",
crate_name))
})format!(
2644 "there are multiple different versions of crate `{crate_name}` in the dependency graph"
2645 );
2646 err.span_note(sp, crate_msg);
2647 }
2648
2649 fn note_adt_version_mismatch(
2650 &self,
2651 err: &mut Diag<'_>,
2652 trait_pred: ty::PolyTraitPredicate<'tcx>,
2653 ) {
2654 let ty::Adt(impl_self_def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2655 else {
2656 return;
2657 };
2658
2659 let impl_self_did = impl_self_def.did();
2660
2661 if impl_self_did.krate == LOCAL_CRATE {
2664 return;
2665 }
2666
2667 let impl_self_path = self.comparable_path(impl_self_did);
2668 let impl_self_crate_name = self.tcx.crate_name(impl_self_did.krate);
2669 let similar_items: UnordSet<_> = self
2670 .tcx
2671 .visible_parent_map(())
2672 .items()
2673 .filter_map(|(&item, _)| {
2674 if impl_self_did == item {
2676 return None;
2677 }
2678 if item.krate == LOCAL_CRATE {
2681 return None;
2682 }
2683 if impl_self_crate_name != self.tcx.crate_name(item.krate) {
2686 return None;
2687 }
2688 if !self.tcx.def_kind(item).is_adt() {
2691 return None;
2692 }
2693 let path = self.comparable_path(item);
2694 let is_similar = path.ends_with(&impl_self_path) || impl_self_path.ends_with(&path);
2697 is_similar.then_some((item, path))
2698 })
2699 .collect();
2700
2701 let mut similar_items =
2702 similar_items.into_items().into_sorted_stable_ord_by_key(|(_, path)| path);
2703 similar_items.dedup();
2704
2705 for (similar_item, _) in similar_items {
2706 err.span_help(self.tcx.def_span(similar_item), "item with same name found");
2707 self.note_two_crate_versions(similar_item.krate, MultiSpan::new(), err);
2708 }
2709 }
2710
2711 fn check_same_name_different_path(
2712 &self,
2713 err: &mut Diag<'_>,
2714 obligation: &PredicateObligation<'tcx>,
2715 trait_pred: ty::PolyTraitPredicate<'tcx>,
2716 ) -> bool {
2717 let mut suggested = false;
2718 let trait_def_id = trait_pred.def_id();
2719 let trait_has_same_params = |other_trait_def_id: DefId| -> bool {
2720 let trait_generics = self.tcx.generics_of(trait_def_id);
2721 let other_trait_generics = self.tcx.generics_of(other_trait_def_id);
2722
2723 if trait_generics.count() != other_trait_generics.count() {
2724 return false;
2725 }
2726 trait_generics.own_params.iter().zip(other_trait_generics.own_params.iter()).all(
2727 |(a, b)| match (&a.kind, &b.kind) {
2728 (ty::GenericParamDefKind::Lifetime, ty::GenericParamDefKind::Lifetime)
2729 | (
2730 ty::GenericParamDefKind::Type { .. },
2731 ty::GenericParamDefKind::Type { .. },
2732 )
2733 | (
2734 ty::GenericParamDefKind::Const { .. },
2735 ty::GenericParamDefKind::Const { .. },
2736 ) => true,
2737 _ => false,
2738 },
2739 )
2740 };
2741 let trait_name = self.tcx.item_name(trait_def_id);
2742 if let Some(other_trait_def_id) = self.tcx.all_traits_including_private().find(|&def_id| {
2743 trait_def_id != def_id
2744 && trait_name == self.tcx.item_name(def_id)
2745 && trait_has_same_params(def_id)
2746 && !self.tcx.is_lang_item(def_id, LangItem::PointeeSized)
2748 && self.predicate_must_hold_modulo_regions(&Obligation::new(
2749 self.tcx,
2750 obligation.cause.clone(),
2751 obligation.param_env,
2752 trait_pred.map_bound(|tr| ty::TraitPredicate {
2753 trait_ref: ty::TraitRef::new(self.tcx, def_id, tr.trait_ref.args),
2754 ..tr
2755 }),
2756 ))
2757 }) {
2758 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements similarly named trait `{1}`, but not `{2}`",
trait_pred.self_ty(),
self.tcx.def_path_str(other_trait_def_id),
trait_pred.print_modifiers_and_trait_path()))
})format!(
2759 "`{}` implements similarly named trait `{}`, but not `{}`",
2760 trait_pred.self_ty(),
2761 self.tcx.def_path_str(other_trait_def_id),
2762 trait_pred.print_modifiers_and_trait_path()
2763 ));
2764 suggested = true;
2765 }
2766 suggested
2767 }
2768
2769 pub fn note_different_trait_with_same_name(
2774 &self,
2775 err: &mut Diag<'_>,
2776 obligation: &PredicateObligation<'tcx>,
2777 trait_pred: ty::PolyTraitPredicate<'tcx>,
2778 ) -> bool {
2779 if self.check_same_trait_different_version(err, trait_pred) {
2780 return true;
2781 }
2782 self.check_same_name_different_path(err, obligation, trait_pred)
2783 }
2784
2785 fn comparable_path(&self, did: DefId) -> String {
2788 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}",
self.tcx.def_path_str(did)))
})format!("::{}", self.tcx.def_path_str(did))
2789 }
2790
2791 pub(super) fn mk_trait_obligation_with_new_self_ty(
2796 &self,
2797 param_env: ty::ParamEnv<'tcx>,
2798 trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
2799 ) -> PredicateObligation<'tcx> {
2800 let trait_pred = trait_ref_and_ty
2801 .map_bound(|(tr, new_self_ty)| tr.with_replaced_self_ty(self.tcx, new_self_ty));
2802
2803 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
2804 }
2805
2806 fn predicate_can_apply(
2809 &self,
2810 param_env: ty::ParamEnv<'tcx>,
2811 pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + TypeFoldable<TyCtxt<'tcx>>,
2812 ) -> bool {
2813 struct ParamToVarFolder<'a, 'tcx> {
2814 infcx: &'a InferCtxt<'tcx>,
2815 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2816 }
2817
2818 impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
2819 fn cx(&self) -> TyCtxt<'tcx> {
2820 self.infcx.tcx
2821 }
2822
2823 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2827 match ty.kind() {
2828 ty::Param(_) => {
2829 let infcx = self.infcx;
2830 *self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
2831 }
2832 &ty::Alias(is_rigid, alias)
2836 if is_rigid == ty::IsRigid::Yes
2837 && ty.has_type_flags(ty::TypeFlags::HAS_TY_PARAM) =>
2838 {
2839 let alias = alias.fold_with(self);
2840 Ty::new_alias(self.cx(), ty::IsRigid::No, alias)
2841 }
2842 _ => ty.super_fold_with(self),
2843 }
2844 }
2845 }
2846
2847 self.probe(|_| {
2848 let cleaned_pred =
2849 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2850
2851 let InferOk { value: cleaned_pred, .. } = self
2852 .infcx
2853 .at(&ObligationCause::dummy(), param_env)
2854 .normalize(Unnormalized::new_wip(cleaned_pred));
2855
2856 let obligation =
2857 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
2858
2859 self.predicate_may_hold(&obligation)
2860 })
2861 }
2862
2863 pub fn note_obligation_cause(
2864 &self,
2865 err: &mut Diag<'_>,
2866 obligation: &PredicateObligation<'tcx>,
2867 ) {
2868 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2871 self.note_obligation_cause_code(
2872 obligation.cause.body_def_id,
2873 err,
2874 obligation.predicate,
2875 obligation.param_env,
2876 obligation.cause.code(),
2877 &mut ::alloc::vec::Vec::new()vec![],
2878 &mut Default::default(),
2879 );
2880 self.suggest_swapping_lhs_and_rhs(
2881 err,
2882 obligation.predicate,
2883 obligation.param_env,
2884 obligation.cause.code(),
2885 );
2886 self.suggest_borrow_for_unsized_closure_return(
2887 obligation.cause.body_def_id,
2888 err,
2889 obligation.predicate,
2890 );
2891 self.suggest_unsized_bound_if_applicable(err, obligation);
2892 if let Some(span) = err.span.primary_span()
2893 && let Some(mut diag) =
2894 self.dcx().steal_non_err(span, StashKey::AssociatedTypeSuggestion)
2895 && let Suggestions::Enabled(ref mut s1) = err.suggestions
2896 && let Suggestions::Enabled(ref mut s2) = diag.suggestions
2897 {
2898 s1.append(s2);
2899 diag.cancel()
2900 }
2901 }
2902 }
2903
2904 pub(super) fn is_recursive_obligation(
2905 &self,
2906 obligated_types: &mut Vec<Ty<'tcx>>,
2907 cause_code: &ObligationCauseCode<'tcx>,
2908 ) -> bool {
2909 if let ObligationCauseCode::BuiltinDerived(data) = cause_code {
2910 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2911 let self_ty = parent_trait_ref.skip_binder().self_ty();
2912 if obligated_types.iter().any(|ot| ot == &self_ty) {
2913 return true;
2914 }
2915 if let ty::Adt(def, args) = self_ty.kind()
2916 && let [arg] = &args[..]
2917 && let ty::GenericArgKind::Type(ty) = arg.kind()
2918 && let ty::Adt(inner_def, _) = ty.kind()
2919 && inner_def == def
2920 {
2921 return true;
2922 }
2923 }
2924 false
2925 }
2926
2927 fn get_standard_error_message(
2928 &self,
2929 trait_predicate: ty::PolyTraitPredicate<'tcx>,
2930 predicate_constness: Option<ty::BoundConstness>,
2931 post_message: String,
2932 long_ty_path: &mut Option<PathBuf>,
2933 ) -> String {
2934 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait bound `{0}` is not satisfied{1}",
self.tcx.short_string(trait_predicate.print_with_bound_constness(predicate_constness),
long_ty_path), post_message))
})format!(
2935 "the trait bound `{}` is not satisfied{post_message}",
2936 self.tcx.short_string(
2937 trait_predicate.print_with_bound_constness(predicate_constness),
2938 long_ty_path,
2939 ),
2940 )
2941 }
2942
2943 fn select_transmute_obligation_for_reporting(
2944 &self,
2945 obligation: &PredicateObligation<'tcx>,
2946 trait_predicate: ty::PolyTraitPredicate<'tcx>,
2947 root_obligation: &PredicateObligation<'tcx>,
2948 ) -> (PredicateObligation<'tcx>, ty::PolyTraitPredicate<'tcx>) {
2949 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
2950 return (obligation.clone(), trait_predicate);
2951 }
2952
2953 let ocx = ObligationCtxt::new(self);
2954 let normalized_predicate = self.tcx.erase_and_anonymize_regions(
2955 self.tcx.instantiate_bound_regions_with_erased(trait_predicate),
2956 );
2957 let trait_ref = normalized_predicate.trait_ref;
2958
2959 let assume = ocx.normalize(
2960 &obligation.cause,
2961 obligation.param_env,
2962 Unnormalized::new_wip(trait_ref.args.const_at(2)),
2963 );
2964
2965 let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
2966 return (obligation.clone(), trait_predicate);
2967 };
2968
2969 let is_normalized_yes = #[allow(non_exhaustive_omitted_patterns)] match rustc_transmute::TransmuteTypeEnv::new(self.tcx).is_transmutable(trait_ref.args.type_at(1),
trait_ref.args.type_at(0), assume) {
rustc_transmute::Answer::Yes => true,
_ => false,
}matches!(
2970 rustc_transmute::TransmuteTypeEnv::new(self.tcx).is_transmutable(
2971 trait_ref.args.type_at(1),
2972 trait_ref.args.type_at(0),
2973 assume,
2974 ),
2975 rustc_transmute::Answer::Yes,
2976 );
2977
2978 if is_normalized_yes
2980 && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
2981 root_obligation.predicate.kind().skip_binder()
2982 && root_pred.def_id() == trait_predicate.def_id()
2983 {
2984 return (root_obligation.clone(), root_obligation.predicate.kind().rebind(root_pred));
2985 }
2986
2987 (obligation.clone(), trait_predicate)
2988 }
2989
2990 fn get_safe_transmute_error_and_reason(
2991 &self,
2992 obligation: PredicateObligation<'tcx>,
2993 trait_pred: ty::PolyTraitPredicate<'tcx>,
2994 span: Span,
2995 ) -> GetSafeTransmuteErrorAndReason {
2996 use rustc_transmute::Answer;
2997 self.probe(|_| {
2998 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
3001 return GetSafeTransmuteErrorAndReason::Default;
3002 }
3003
3004 let trait_pred = self.tcx.erase_and_anonymize_regions(
3006 self.tcx.instantiate_bound_regions_with_erased(trait_pred),
3007 );
3008
3009 let ocx = ObligationCtxt::new(self);
3010 let assume = ocx.normalize(
3011 &obligation.cause,
3012 obligation.param_env,
3013 Unnormalized::new_wip(trait_pred.trait_ref.args.const_at(2)),
3014 );
3015
3016 let Some(assume) = rustc_transmute::Assume::from_const(self.infcx.tcx, assume) else {
3017 self.dcx().span_delayed_bug(
3018 span,
3019 "Unable to construct rustc_transmute::Assume where it was previously possible",
3020 );
3021 return GetSafeTransmuteErrorAndReason::Silent;
3022 };
3023
3024 let dst = trait_pred.trait_ref.args.type_at(0);
3025 let src = trait_pred.trait_ref.args.type_at(1);
3026 let err_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` cannot be safely transmuted into `{1}`",
src, dst))
})format!("`{src}` cannot be safely transmuted into `{dst}`");
3027
3028 match rustc_transmute::TransmuteTypeEnv::new(self.infcx.tcx)
3029 .is_transmutable(src, dst, assume)
3030 {
3031 Answer::No(reason) => {
3032 let safe_transmute_explanation = match reason {
3033 rustc_transmute::Reason::SrcIsNotYetSupported => {
3034 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("analyzing the transmutability of `{0}` is not yet supported",
src))
})format!("analyzing the transmutability of `{src}` is not yet supported")
3035 }
3036 rustc_transmute::Reason::DstIsNotYetSupported => {
3037 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("analyzing the transmutability of `{0}` is not yet supported",
dst))
})format!("analyzing the transmutability of `{dst}` is not yet supported")
3038 }
3039 rustc_transmute::Reason::DstIsBitIncompatible => {
3040 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("at least one value of `{0}` isn\'t a bit-valid value of `{1}`",
src, dst))
})format!(
3041 "at least one value of `{src}` isn't a bit-valid value of `{dst}`"
3042 )
3043 }
3044 rustc_transmute::Reason::DstUninhabited => {
3045 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is uninhabited", dst))
})format!("`{dst}` is uninhabited")
3046 }
3047 rustc_transmute::Reason::DstMayHaveSafetyInvariants => {
3048 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` may carry safety invariants",
dst))
})format!("`{dst}` may carry safety invariants")
3049 }
3050 rustc_transmute::Reason::DstIsTooBig => {
3051 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the size of `{0}` is smaller than the size of `{1}`",
src, dst))
})format!("the size of `{src}` is smaller than the size of `{dst}`")
3052 }
3053 rustc_transmute::Reason::DstRefIsTooBig {
3054 src,
3055 src_size,
3056 dst,
3057 dst_size,
3058 } => {
3059 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the size of `{0}` ({1} bytes) is smaller than that of `{2}` ({3} bytes)",
src, src_size, dst, dst_size))
})format!(
3060 "the size of `{src}` ({src_size} bytes) \
3061 is smaller than that of `{dst}` ({dst_size} bytes)"
3062 )
3063 }
3064 rustc_transmute::Reason::SrcSizeOverflow => {
3065 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
src))
})format!(
3066 "values of the type `{src}` are too big for the target architecture"
3067 )
3068 }
3069 rustc_transmute::Reason::DstSizeOverflow => {
3070 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
dst))
})format!(
3071 "values of the type `{dst}` are too big for the target architecture"
3072 )
3073 }
3074 rustc_transmute::Reason::DstHasStricterAlignment {
3075 src_min_align,
3076 dst_min_align,
3077 } => {
3078 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the minimum alignment of `{0}` ({1}) should be greater than that of `{2}` ({3})",
src, src_min_align, dst, dst_min_align))
})format!(
3079 "the minimum alignment of `{src}` ({src_min_align}) should be \
3080 greater than that of `{dst}` ({dst_min_align})"
3081 )
3082 }
3083 rustc_transmute::Reason::DstIsMoreUnique => {
3084 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is a shared reference, but `{1}` is a unique reference",
src, dst))
})format!(
3085 "`{src}` is a shared reference, but `{dst}` is a unique reference"
3086 )
3087 }
3088 rustc_transmute::Reason::TypeError => {
3090 return GetSafeTransmuteErrorAndReason::Silent;
3091 }
3092 rustc_transmute::Reason::SrcLayoutUnknown => {
3093 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", src))
})format!("`{src}` has an unknown layout")
3094 }
3095 rustc_transmute::Reason::DstLayoutUnknown => {
3096 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", dst))
})format!("`{dst}` has an unknown layout")
3097 }
3098 };
3099 GetSafeTransmuteErrorAndReason::Error {
3100 err_msg,
3101 safe_transmute_explanation: Some(safe_transmute_explanation),
3102 }
3103 }
3104 Answer::Yes => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("Inconsistent rustc_transmute::is_transmutable(...) result, got Yes"))span_bug!(
3106 span,
3107 "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
3108 ),
3109 Answer::If(_) => GetSafeTransmuteErrorAndReason::Error {
3114 err_msg,
3115 safe_transmute_explanation: None,
3116 },
3117 }
3118 })
3119 }
3120
3121 fn find_explicit_cast_type(
3124 &self,
3125 param_env: ty::ParamEnv<'tcx>,
3126 found_ty: Ty<'tcx>,
3127 self_ty: Ty<'tcx>,
3128 ) -> Option<Ty<'tcx>> {
3129 let ty::Ref(region, inner_ty, mutbl) = *found_ty.kind() else {
3130 return None;
3131 };
3132
3133 let mut derefs = (self.autoderef_steps)(inner_ty).into_iter();
3134 derefs.next(); let deref_target = derefs.into_iter().next()?.0;
3136
3137 let cast_ty = Ty::new_ref(self.tcx, region, deref_target, mutbl);
3138
3139 let Some(from_def_id) = self.tcx.get_diagnostic_item(sym::From) else {
3140 return None;
3141 };
3142 let Some(try_from_def_id) = self.tcx.get_diagnostic_item(sym::TryFrom) else {
3143 return None;
3144 };
3145
3146 if self.has_impl_for_type(
3147 param_env,
3148 ty::TraitRef::new(
3149 self.tcx,
3150 from_def_id,
3151 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3152 ),
3153 ) {
3154 Some(cast_ty)
3155 } else if self.has_impl_for_type(
3156 param_env,
3157 ty::TraitRef::new(
3158 self.tcx,
3159 try_from_def_id,
3160 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3161 ),
3162 ) {
3163 Some(cast_ty)
3164 } else {
3165 None
3166 }
3167 }
3168
3169 fn has_impl_for_type(
3170 &self,
3171 param_env: ty::ParamEnv<'tcx>,
3172 trait_ref: ty::TraitRef<'tcx>,
3173 ) -> bool {
3174 let obligation = Obligation::new(
3175 self.tcx,
3176 ObligationCause::dummy(),
3177 param_env,
3178 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive },
3179 );
3180
3181 self.predicate_must_hold_modulo_regions(&obligation)
3182 }
3183
3184 fn add_tuple_trait_message(
3185 &self,
3186 obligation_cause_code: &ObligationCauseCode<'tcx>,
3187 err: &mut Diag<'_>,
3188 ) {
3189 match obligation_cause_code {
3190 ObligationCauseCode::RustCall => {
3191 err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
3192 }
3193 ObligationCauseCode::WhereClause(def_id, _) if self.tcx.is_fn_trait(*def_id) => {
3194 err.code(E0059);
3195 err.primary_message(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type parameter to bare `{0}` trait must be a tuple",
self.tcx.def_path_str(*def_id)))
})format!(
3196 "type parameter to bare `{}` trait must be a tuple",
3197 self.tcx.def_path_str(*def_id)
3198 ));
3199 }
3200 _ => {}
3201 }
3202 }
3203
3204 fn try_to_add_help_message(
3205 &self,
3206 root_obligation: &PredicateObligation<'tcx>,
3207 obligation: &PredicateObligation<'tcx>,
3208 trait_predicate: ty::PolyTraitPredicate<'tcx>,
3209 err: &mut Diag<'_>,
3210 span: Span,
3211 is_fn_trait: bool,
3212 suggested: bool,
3213 ) {
3214 let body_def_id = obligation.cause.body_def_id;
3215 let span = if let ObligationCauseCode::BinOp { rhs_span, .. } = obligation.cause.code() {
3216 *rhs_span
3217 } else {
3218 span
3219 };
3220
3221 let trait_def_id = trait_predicate.def_id();
3223 if is_fn_trait
3224 && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
3225 obligation.param_env,
3226 trait_predicate.self_ty(),
3227 trait_predicate.skip_binder().polarity,
3228 )
3229 {
3230 self.add_help_message_for_fn_trait(trait_predicate, err, implemented_kind, params);
3231 } else if !trait_predicate.has_non_region_infer()
3232 && self.predicate_can_apply(obligation.param_env, trait_predicate)
3233 {
3234 self.suggest_restricting_param_bound(
3242 err,
3243 trait_predicate,
3244 None,
3245 obligation.cause.body_def_id,
3246 );
3247 } else if trait_def_id.is_local()
3248 && self.tcx.trait_impls_of(trait_def_id).is_empty()
3249 && !self.tcx.trait_is_auto(trait_def_id)
3250 && !self.tcx.trait_is_alias(trait_def_id)
3251 && trait_predicate.polarity() == ty::PredicatePolarity::Positive
3252 {
3253 err.span_help(
3254 self.tcx.def_span(trait_def_id),
3255 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this trait has no implementations, consider adding one"))msg!("this trait has no implementations, consider adding one"),
3256 );
3257 } else if !suggested && trait_predicate.polarity() == ty::PredicatePolarity::Positive {
3258 let impl_candidates = self.find_similar_impl_candidates(trait_predicate);
3260 if !self.report_similar_impl_candidates(
3261 &impl_candidates,
3262 obligation,
3263 trait_predicate,
3264 body_def_id,
3265 err,
3266 true,
3267 obligation.param_env,
3268 ) {
3269 self.report_similar_impl_candidates_for_root_obligation(
3270 obligation,
3271 trait_predicate,
3272 body_def_id,
3273 err,
3274 );
3275 }
3276
3277 self.suggest_convert_to_slice(
3278 err,
3279 obligation,
3280 trait_predicate,
3281 impl_candidates.as_slice(),
3282 span,
3283 );
3284
3285 self.suggest_tuple_wrapping(err, root_obligation, obligation);
3286 }
3287 self.suggest_shadowed_inherent_method(err, obligation, trait_predicate);
3288 }
3289
3290 fn add_help_message_for_fn_trait(
3291 &self,
3292 trait_pred: ty::PolyTraitPredicate<'tcx>,
3293 err: &mut Diag<'_>,
3294 implemented_kind: ty::ClosureKind,
3295 params: ty::Binder<'tcx, Ty<'tcx>>,
3296 ) {
3297 let selected_kind = self
3304 .tcx
3305 .fn_trait_kind_from_def_id(trait_pred.def_id())
3306 .expect("expected to map DefId to ClosureKind");
3307 if !implemented_kind.extends(selected_kind) {
3308 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements `{1}`, but it must implement `{2}`, which is more general",
trait_pred.skip_binder().self_ty(), implemented_kind,
selected_kind))
})format!(
3309 "`{}` implements `{}`, but it must implement `{}`, which is more general",
3310 trait_pred.skip_binder().self_ty(),
3311 implemented_kind,
3312 selected_kind
3313 ));
3314 }
3315
3316 let ty::Tuple(given) = *params.skip_binder().kind() else {
3318 return;
3319 };
3320
3321 let expected_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
3322 let ty::Tuple(expected) = *expected_ty.kind() else {
3323 return;
3324 };
3325
3326 if expected.len() != given.len() {
3327 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected a closure taking {0} argument{1}, but one taking {2} argument{3} was given",
given.len(), if given.len() == 1 { "" } else { "s" },
expected.len(), if expected.len() == 1 { "" } else { "s" }))
})format!(
3329 "expected a closure taking {} argument{}, but one taking {} argument{} was given",
3330 given.len(),
3331 pluralize!(given.len()),
3332 expected.len(),
3333 pluralize!(expected.len()),
3334 ));
3335 return;
3336 }
3337
3338 let given_ty = Ty::new_fn_ptr(
3339 self.tcx,
3340 params.rebind(self.tcx.mk_fn_sig_safe_rust_abi(given, self.tcx.types.unit)),
3341 );
3342 let expected_ty = Ty::new_fn_ptr(
3343 self.tcx,
3344 trait_pred.rebind(self.tcx.mk_fn_sig_safe_rust_abi(expected, self.tcx.types.unit)),
3345 );
3346
3347 if !self.same_type_modulo_infer(given_ty, expected_ty) {
3348 let (expected_args, given_args) = self.cmp(expected_ty, given_ty);
3350 err.note_expected_found(
3351 "a closure with signature",
3352 expected_args,
3353 "a closure with signature",
3354 given_args,
3355 );
3356 }
3357 }
3358
3359 fn report_closure_error(
3360 &self,
3361 obligation: &PredicateObligation<'tcx>,
3362 closure_def_id: DefId,
3363 found_kind: ty::ClosureKind,
3364 kind: ty::ClosureKind,
3365 trait_prefix: &'static str,
3366 ) -> Diag<'a> {
3367 let closure_span = self.tcx.def_span(closure_def_id);
3368
3369 let mut err = ClosureKindMismatch {
3370 closure_span,
3371 expected: kind,
3372 found: found_kind,
3373 cause_span: obligation.cause.span,
3374 trait_prefix,
3375 fn_once_label: None,
3376 fn_mut_label: None,
3377 };
3378
3379 if let Some(typeck_results) = &self.typeck_results {
3382 let hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id.expect_local());
3383 match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
3384 (ty::ClosureKind::FnOnce, Some((span, place))) => {
3385 err.fn_once_label = Some(ClosureFnOnceLabel {
3386 span: *span,
3387 place: ty::place_to_string_for_capture(self.tcx, place),
3388 trait_prefix,
3389 })
3390 }
3391 (ty::ClosureKind::FnMut, Some((span, place))) => {
3392 err.fn_mut_label = Some(ClosureFnMutLabel {
3393 span: *span,
3394 place: ty::place_to_string_for_capture(self.tcx, place),
3395 trait_prefix,
3396 })
3397 }
3398 _ => {}
3399 }
3400 }
3401
3402 self.dcx().create_err(err)
3403 }
3404
3405 fn report_cyclic_signature_error(
3406 &self,
3407 obligation: &PredicateObligation<'tcx>,
3408 found_trait_ref: ty::TraitRef<'tcx>,
3409 expected_trait_ref: ty::TraitRef<'tcx>,
3410 terr: TypeError<'tcx>,
3411 ) -> Diag<'a> {
3412 let self_ty = found_trait_ref.self_ty();
3413 let (cause, terr) = if let ty::Closure(def_id, _) = *self_ty.kind() {
3414 (
3415 ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
3416 TypeError::CyclicTy(self_ty),
3417 )
3418 } else {
3419 (obligation.cause.clone(), terr)
3420 };
3421 self.report_and_explain_type_error(
3422 TypeTrace::trait_refs(&cause, expected_trait_ref, found_trait_ref),
3423 obligation.param_env,
3424 terr,
3425 )
3426 }
3427
3428 fn report_signature_mismatch_error(
3429 &self,
3430 obligation: &PredicateObligation<'tcx>,
3431 span: Span,
3432 found_trait_ref: ty::TraitRef<'tcx>,
3433 expected_trait_ref: ty::TraitRef<'tcx>,
3434 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3435 let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
3436 let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
3437
3438 expected_trait_ref.self_ty().error_reported()?;
3439 let found_trait_ty = found_trait_ref.self_ty();
3440
3441 let found_did = match *found_trait_ty.kind() {
3442 ty::Closure(did, _) | ty::FnDef(did, _) | ty::Coroutine(did, ..) => Some(did),
3443 _ => None,
3444 };
3445
3446 let found_node = found_did.and_then(|did| self.tcx.hir_get_if_local(did));
3447 let found_span = found_did.and_then(|did| self.tcx.hir_span_if_local(did));
3448
3449 if !self.reported_signature_mismatch.borrow_mut().insert((span, found_span)) {
3450 return Err(self.dcx().span_delayed_bug(span, "already_reported"));
3453 }
3454
3455 let mut not_tupled = false;
3456
3457 let found = match found_trait_ref.args.type_at(1).kind() {
3458 ty::Tuple(tys) => ::alloc::vec::from_elem(ArgKind::empty(), tys.len())vec![ArgKind::empty(); tys.len()],
3459 _ => {
3460 not_tupled = true;
3461 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ArgKind::empty()]))vec![ArgKind::empty()]
3462 }
3463 };
3464
3465 let expected_ty = expected_trait_ref.args.type_at(1);
3466 let expected = match expected_ty.kind() {
3467 ty::Tuple(tys) => {
3468 tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
3469 }
3470 _ => {
3471 not_tupled = true;
3472 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ArgKind::Arg("_".to_owned(), expected_ty.to_string())]))vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())]
3473 }
3474 };
3475
3476 if !self.tcx.is_lang_item(expected_trait_ref.def_id, LangItem::Coroutine) && not_tupled {
3482 return Ok(self.report_and_explain_type_error(
3483 TypeTrace::trait_refs(&obligation.cause, expected_trait_ref, found_trait_ref),
3484 obligation.param_env,
3485 ty::error::TypeError::Mismatch,
3486 ));
3487 }
3488 if found.len() != expected.len() {
3489 let (closure_span, closure_arg_span, found) = found_did
3490 .and_then(|did| {
3491 let node = self.tcx.hir_get_if_local(did)?;
3492 let (found_span, closure_arg_span, found) = self.get_fn_like_arguments(node)?;
3493 Some((Some(found_span), closure_arg_span, found))
3494 })
3495 .unwrap_or((found_span, None, found));
3496
3497 if found.len() != expected.len() {
3503 return Ok(self.report_arg_count_mismatch(
3504 span,
3505 closure_span,
3506 expected,
3507 found,
3508 found_trait_ty.is_closure(),
3509 closure_arg_span,
3510 ));
3511 }
3512 }
3513 Ok(self.report_closure_arg_mismatch(
3514 span,
3515 found_span,
3516 found_trait_ref,
3517 expected_trait_ref,
3518 obligation.cause.code(),
3519 found_node,
3520 obligation.param_env,
3521 ))
3522 }
3523
3524 pub fn get_fn_like_arguments(
3529 &self,
3530 node: Node<'_>,
3531 ) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
3532 let sm = self.tcx.sess.source_map();
3533 Some(match node {
3534 Node::Expr(&hir::Expr {
3535 kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
3536 ..
3537 }) => (
3538 fn_decl_span,
3539 fn_arg_span,
3540 self.tcx
3541 .hir_body(body)
3542 .params
3543 .iter()
3544 .map(|arg| {
3545 if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat
3546 {
3547 Some(ArgKind::Tuple(
3548 Some(span),
3549 args.iter()
3550 .map(|pat| {
3551 sm.span_to_snippet(pat.span)
3552 .ok()
3553 .map(|snippet| (snippet, "_".to_owned()))
3554 })
3555 .collect::<Option<Vec<_>>>()?,
3556 ))
3557 } else {
3558 let name = sm.span_to_snippet(arg.pat.span).ok()?;
3559 Some(ArgKind::Arg(name, "_".to_owned()))
3560 }
3561 })
3562 .collect::<Option<Vec<ArgKind>>>()?,
3563 ),
3564 Node::Item(&hir::Item { kind: hir::ItemKind::Fn { ref sig, .. }, .. })
3565 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
3566 | Node::TraitItem(&hir::TraitItem {
3567 kind: hir::TraitItemKind::Fn(ref sig, _), ..
3568 })
3569 | Node::ForeignItem(&hir::ForeignItem {
3570 kind: hir::ForeignItemKind::Fn(ref sig, _, _),
3571 ..
3572 }) => (
3573 sig.span,
3574 None,
3575 sig.decl
3576 .inputs
3577 .iter()
3578 .map(|arg| match arg.kind {
3579 hir::TyKind::Tup(tys) => ArgKind::Tuple(
3580 Some(arg.span),
3581 ::alloc::vec::from_elem(("_".to_owned(), "_".to_owned()), tys.len())vec![("_".to_owned(), "_".to_owned()); tys.len()],
3582 ),
3583 _ => ArgKind::empty(),
3584 })
3585 .collect::<Vec<ArgKind>>(),
3586 ),
3587 Node::Ctor(variant_data) => {
3588 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| self.tcx.hir_span(id));
3589 (span, None, ::alloc::vec::from_elem(ArgKind::empty(), variant_data.fields().len())vec![ArgKind::empty(); variant_data.fields().len()])
3590 }
3591 _ => {
::core::panicking::panic_fmt(format_args!("non-FnLike node found: {0:?}",
node));
}panic!("non-FnLike node found: {node:?}"),
3592 })
3593 }
3594
3595 pub fn report_arg_count_mismatch(
3599 &self,
3600 span: Span,
3601 found_span: Option<Span>,
3602 expected_args: Vec<ArgKind>,
3603 found_args: Vec<ArgKind>,
3604 is_closure: bool,
3605 closure_arg_span: Option<Span>,
3606 ) -> Diag<'a> {
3607 let kind = if is_closure { "closure" } else { "function" };
3608
3609 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
3610 let arg_length = arguments.len();
3611 let distinct = #[allow(non_exhaustive_omitted_patterns)] match other {
&[ArgKind::Tuple(..)] => true,
_ => false,
}matches!(other, &[ArgKind::Tuple(..)]);
3612 match (arg_length, arguments.get(0)) {
3613 (1, Some(ArgKind::Tuple(_, fields))) => {
3614 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a single {0}-tuple as argument",
fields.len()))
})format!("a single {}-tuple as argument", fields.len())
3615 }
3616 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}argument{2}", arg_length,
if distinct && arg_length > 1 { "distinct " } else { "" },
if arg_length == 1 { "" } else { "s" }))
})format!(
3617 "{} {}argument{}",
3618 arg_length,
3619 if distinct && arg_length > 1 { "distinct " } else { "" },
3620 pluralize!(arg_length)
3621 ),
3622 }
3623 };
3624
3625 let expected_str = args_str(&expected_args, &found_args);
3626 let found_str = args_str(&found_args, &expected_args);
3627
3628 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is expected to take {1}, but it takes {2}",
kind, expected_str, found_str))
})).with_code(E0593)
}struct_span_code_err!(
3629 self.dcx(),
3630 span,
3631 E0593,
3632 "{} is expected to take {}, but it takes {}",
3633 kind,
3634 expected_str,
3635 found_str,
3636 );
3637
3638 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0} that takes {1}", kind,
expected_str))
})format!("expected {kind} that takes {expected_str}"));
3639
3640 if let Some(found_span) = found_span {
3641 err.span_label(found_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("takes {0}", found_str))
})format!("takes {found_str}"));
3642
3643 if found_args.is_empty() && is_closure {
3647 let underscores = ::alloc::vec::from_elem("_", expected_args.len())vec!["_"; expected_args.len()].join(", ");
3648 err.span_suggestion_verbose(
3649 closure_arg_span.unwrap_or(found_span),
3650 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider changing the closure to take and ignore the expected argument{0}",
if expected_args.len() == 1 { "" } else { "s" }))
})format!(
3651 "consider changing the closure to take and ignore the expected argument{}",
3652 pluralize!(expected_args.len())
3653 ),
3654 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", underscores))
})format!("|{underscores}|"),
3655 Applicability::MachineApplicable,
3656 );
3657 }
3658
3659 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
3660 if fields.len() == expected_args.len() {
3661 let sugg = fields
3662 .iter()
3663 .map(|(name, _)| name.to_owned())
3664 .collect::<Vec<String>>()
3665 .join(", ");
3666 err.span_suggestion_verbose(
3667 found_span,
3668 "change the closure to take multiple arguments instead of a single tuple",
3669 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", sugg))
})format!("|{sugg}|"),
3670 Applicability::MachineApplicable,
3671 );
3672 }
3673 }
3674 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
3675 && fields.len() == found_args.len()
3676 && is_closure
3677 {
3678 let sugg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|({0}){1}|",
found_args.iter().map(|arg|
match arg {
ArgKind::Arg(name, _) => name.to_owned(),
_ => "_".to_owned(),
}).collect::<Vec<String>>().join(", "),
if found_args.iter().any(|arg|
match arg { ArgKind::Arg(_, ty) => ty != "_", _ => false, })
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": ({0})",
fields.iter().map(|(_, ty)|
ty.to_owned()).collect::<Vec<String>>().join(", ")))
})
} else { String::new() }))
})format!(
3679 "|({}){}|",
3680 found_args
3681 .iter()
3682 .map(|arg| match arg {
3683 ArgKind::Arg(name, _) => name.to_owned(),
3684 _ => "_".to_owned(),
3685 })
3686 .collect::<Vec<String>>()
3687 .join(", "),
3688 if found_args.iter().any(|arg| match arg {
3690 ArgKind::Arg(_, ty) => ty != "_",
3691 _ => false,
3692 }) {
3693 format!(
3694 ": ({})",
3695 fields
3696 .iter()
3697 .map(|(_, ty)| ty.to_owned())
3698 .collect::<Vec<String>>()
3699 .join(", ")
3700 )
3701 } else {
3702 String::new()
3703 },
3704 );
3705 err.span_suggestion_verbose(
3706 found_span,
3707 "change the closure to accept a tuple instead of individual arguments",
3708 sugg,
3709 Applicability::MachineApplicable,
3710 );
3711 }
3712 }
3713
3714 err
3715 }
3716
3717 pub fn type_implements_fn_trait(
3721 &self,
3722 param_env: ty::ParamEnv<'tcx>,
3723 ty: ty::Binder<'tcx, Ty<'tcx>>,
3724 polarity: ty::PredicatePolarity,
3725 ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
3726 self.commit_if_ok(|_| {
3727 for trait_def_id in [
3728 self.tcx.lang_items().fn_trait(),
3729 self.tcx.lang_items().fn_mut_trait(),
3730 self.tcx.lang_items().fn_once_trait(),
3731 ] {
3732 let Some(trait_def_id) = trait_def_id else { continue };
3733 let var = self.next_ty_var(DUMMY_SP);
3736 let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
3738 let obligation = Obligation::new(
3739 self.tcx,
3740 ObligationCause::dummy(),
3741 param_env,
3742 ty.rebind(ty::TraitPredicate { trait_ref, polarity }),
3743 );
3744 let ocx = ObligationCtxt::new(self);
3745 ocx.register_obligation(obligation);
3746 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
3747 return Ok((
3748 self.tcx
3749 .fn_trait_kind_from_def_id(trait_def_id)
3750 .expect("expected to map DefId to ClosureKind"),
3751 ty.rebind(self.resolve_vars_if_possible(var)),
3752 ));
3753 }
3754 }
3755
3756 Err(())
3757 })
3758 }
3759
3760 fn report_not_const_evaluatable_error(
3761 &self,
3762 obligation: &PredicateObligation<'tcx>,
3763 span: Span,
3764 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3765 if !self.tcx.features().generic_const_exprs()
3766 && !self.tcx.features().min_generic_const_args()
3767 {
3768 let guar = self
3769 .dcx()
3770 .struct_span_err(span, "constant expression depends on a generic parameter")
3771 .with_note("this may fail depending on what value the parameter takes")
3778 .emit();
3779 return Err(guar);
3780 }
3781
3782 match obligation.predicate.kind().skip_binder() {
3783 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => match ct.kind() {
3784 ty::ConstKind::Alias(_, alias_const) => {
3785 let mut err =
3786 self.dcx().struct_span_err(span, "unconstrained generic constant");
3787 let const_span = alias_const.kind.def_span(self.tcx);
3788
3789 let const_ty = alias_const.type_of(self.tcx).skip_norm_wip();
3790 let cast = if const_ty != self.tcx.types.usize { " as usize" } else { "" };
3791 let msg = "try adding a `where` bound";
3792 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(const_span) {
3793 let code = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); {0}{1}]:", snippet, cast))
})format!("[(); {snippet}{cast}]:");
3794 let suggestion_def_id = if let ObligationCauseCode::CompareImplItem {
3795 trait_item_def_id,
3796 ..
3797 } = obligation.cause.code()
3798 {
3799 trait_item_def_id.as_local()
3800 } else {
3801 Some(obligation.cause.body_def_id)
3802 };
3803 if let Some(suggestion_def_id) = suggestion_def_id
3804 && let Some(generics) = self.tcx.hir_get_generics(suggestion_def_id)
3805 {
3806 err.span_suggestion_verbose(
3807 generics.tail_span_for_predicate_suggestion(),
3808 msg,
3809 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}",
generics.add_where_or_trailing_comma(), code))
})format!("{} {code}", generics.add_where_or_trailing_comma()),
3810 Applicability::MaybeIncorrect,
3811 );
3812 } else {
3813 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: where {1}", msg, code))
})format!("{msg}: where {code}"));
3814 };
3815 } else {
3816 err.help(msg);
3817 }
3818 Ok(err)
3819 }
3820 ty::ConstKind::Expr(_) => {
3821 let err = self
3822 .dcx()
3823 .struct_span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unconstrained generic constant `{0}`",
ct))
})format!("unconstrained generic constant `{ct}`"));
3824 Ok(err)
3825 }
3826 _ => {
3827 ::rustc_middle::util::bug::bug_fmt(format_args!("const evaluatable failed for non-alias const `{0:?}`",
ct));bug!("const evaluatable failed for non-alias const `{ct:?}`");
3828 }
3829 },
3830 _ => {
3831 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpected non-ConstEvaluatable predicate, this should not be reachable"))span_bug!(
3832 span,
3833 "unexpected non-ConstEvaluatable predicate, this should not be reachable"
3834 )
3835 }
3836 }
3837 }
3838}