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_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_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::AliasRelate { .. }
739 | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType { .. }) => {
740 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("Unexpected `Predicate` for `SelectionError`: `{0:?}`",
obligation))span_bug!(
741 span,
742 "Unexpected `Predicate` for `SelectionError`: `{:?}`",
743 obligation
744 )
745 }
746 }
747 }
748
749 SelectionError::SignatureMismatch(SignatureMismatchData {
750 found_trait_ref,
751 expected_trait_ref,
752 terr: terr @ TypeError::CyclicTy(_),
753 }) => self.report_cyclic_signature_error(
754 &obligation,
755 found_trait_ref,
756 expected_trait_ref,
757 terr,
758 ),
759 SelectionError::SignatureMismatch(SignatureMismatchData {
760 found_trait_ref,
761 expected_trait_ref,
762 terr: _,
763 }) => {
764 match self.report_signature_mismatch_error(
765 &obligation,
766 span,
767 found_trait_ref,
768 expected_trait_ref,
769 ) {
770 Ok(err) => err,
771 Err(guar) => return guar,
772 }
773 }
774
775 SelectionError::TraitDynIncompatible(did) => {
776 let violations = self.tcx.dyn_compatibility_violations(did);
777 report_dyn_incompatibility(self.tcx, span, None, did, violations)
778 }
779
780 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
781 ::rustc_middle::util::bug::bug_fmt(format_args!("MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"))bug!(
782 "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
783 )
784 }
785 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
786 match self.report_not_const_evaluatable_error(&obligation, span) {
787 Ok(err) => err,
788 Err(guar) => return guar,
789 }
790 }
791
792 SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(guar))
794 | SelectionError::Overflow(OverflowError::Error(guar)) => {
795 self.set_tainted_by_errors(guar);
796 return guar;
797 }
798
799 SelectionError::Overflow(_) => {
800 ::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");
801 }
802
803 SelectionError::ConstArgHasWrongType { ct, ct_ty, expected_ty } => {
804 let expected_ty_str = self.tcx.short_string(expected_ty, &mut long_ty_file);
805 let ct_str = self.tcx.short_string(ct, &mut long_ty_file);
806 let mut diag = self.dcx().struct_span_err(
807 span,
808 ::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}`"),
809 );
810 diag.long_ty_path = long_ty_file;
811
812 self.note_type_err(
813 &mut diag,
814 &obligation.cause,
815 None,
816 None,
817 TypeError::Sorts(ty::error::ExpectedFound::new(expected_ty, ct_ty)),
818 false,
819 None,
820 );
821 diag
822 }
823 };
824
825 self.note_obligation_cause(&mut err, &obligation);
826 err.emit()
827 }
828}
829
830impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
831 pub(super) fn apply_do_not_recommend(
832 &self,
833 obligation: &mut PredicateObligation<'tcx>,
834 root_obligation: &PredicateObligation<'tcx>,
835 ) -> bool {
836 let mut base_cause = obligation.cause.code().clone();
837 let mut applied_do_not_recommend = false;
838 loop {
839 if let ObligationCauseCode::ImplDerived(ref c) = base_cause {
840 if self.tcx.do_not_recommend_impl(c.impl_or_alias_def_id) {
841 let code = (*c.derived.parent_code).clone();
842 if code == *root_obligation.cause.code()
845 && root_obligation.cause.span.eq_ctxt(obligation.cause.span)
846 && !root_obligation.cause.span.contains(obligation.cause.span)
847 {
848 obligation.cause.span = root_obligation.cause.span;
849 }
850 obligation.cause.map_code(|_| code);
851 obligation.predicate = c.derived.parent_trait_pred.upcast(self.tcx);
852 applied_do_not_recommend = true;
853 }
854 }
855 if let Some(parent_cause) = base_cause.parent() {
856 base_cause = parent_cause.clone();
857 } else {
858 break;
859 }
860 }
861
862 applied_do_not_recommend
863 }
864
865 fn report_host_effect_error(
866 &self,
867 predicate: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
868 main_obligation: &PredicateObligation<'tcx>,
869 span: Span,
870 ) -> Diag<'a> {
871 let trait_ref = predicate.map_bound(|predicate| ty::TraitPredicate {
875 trait_ref: predicate.trait_ref,
876 polarity: ty::PredicatePolarity::Positive,
877 });
878 let mut file = None;
879
880 let err_msg = self.get_standard_error_message(
881 trait_ref,
882 Some(predicate.constness()),
883 String::new(),
884 &mut file,
885 );
886 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);
887 *diag.long_ty_path() = file;
888 let obligation = Obligation::new(
889 self.tcx,
890 ObligationCause::dummy(),
891 main_obligation.param_env,
892 trait_ref,
893 );
894 if !self.predicate_may_hold(&obligation) {
895 diag.downgrade_to_delayed_bug();
896 }
897
898 if let Ok(Some(ImplSource::UserDefined(impl_data))) =
899 self.enter_forall(trait_ref, |trait_ref_for_select| {
900 SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref_for_select))
901 })
902 {
903 let impl_did = impl_data.impl_def_id;
904 let trait_did = trait_ref.def_id();
905 let impl_span = self.tcx.def_span(impl_did);
906 let trait_name = self.tcx.item_name(trait_did);
907
908 if self.tcx.is_const_trait(trait_did) && !self.tcx.is_const_trait_impl(impl_did) {
909 if !impl_did.is_local() {
910 diag.span_note(
911 impl_span,
912 ::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`"),
913 );
914 }
915
916 if let Some(command) =
917 {
{
'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())
918 .flatten()
919 {
920 let (_, format_args) = self.on_unimplemented_components(
921 trait_ref,
922 main_obligation,
923 diag.long_ty_path(),
924 );
925 let CustomDiagnostic { message, label, notes, parent_label: _ } =
926 command.eval(None, &format_args);
927
928 if let Some(message) = message {
929 diag.primary_message(message);
930 }
931 if let Some(label) = label {
932 diag.span_label(span, label);
933 }
934 for note in notes {
935 diag.note(note);
936 }
937 } else if let Some(impl_did) = impl_did.as_local()
938 && let item = self.tcx.hir_expect_item(impl_did)
939 && let hir::ItemKind::Impl(item) = item.kind
940 && let Some(of_trait) = item.of_trait
941 {
942 diag.span_suggestion_verbose(
944 of_trait.trait_ref.path.span.shrink_to_lo(),
945 ::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`"),
946 "const ".to_string(),
947 Applicability::MaybeIncorrect,
948 );
949 }
950 }
951 } else if let ty::Param(param) = trait_ref.self_ty().skip_binder().kind()
952 && let Some(generics) =
953 self.tcx.hir_node_by_def_id(main_obligation.cause.body_id).generics()
954 {
955 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!(
956 "[const] {}",
957 trait_ref.map_bound(|tr| tr.trait_ref).print_trait_sugared(),
958 ));
959 ty::suggest_constraining_type_param(
960 self.tcx,
961 generics,
962 &mut diag,
963 param.name.as_str(),
964 &constraint,
965 Some(trait_ref.def_id()),
966 None,
967 );
968 }
969 diag
970 }
971
972 fn emit_specialized_closure_kind_error(
973 &self,
974 obligation: &PredicateObligation<'tcx>,
975 mut trait_pred: ty::PolyTraitPredicate<'tcx>,
976 ) -> Option<ErrorGuaranteed> {
977 if self.tcx.is_lang_item(trait_pred.def_id(), LangItem::AsyncFnKindHelper) {
980 let mut code = obligation.cause.code();
981 if let ObligationCauseCode::FunctionArg { parent_code, .. } = code {
983 code = &**parent_code;
984 }
985 if let Some((_, Some(parent))) = code.parent_with_predicate() {
987 trait_pred = parent;
988 }
989 }
990
991 let self_ty = trait_pred.self_ty().skip_binder();
992
993 let (expected_kind, trait_prefix) =
994 if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) {
995 (expected_kind, "")
996 } else if let Some(expected_kind) =
997 self.tcx.async_fn_trait_kind_from_def_id(trait_pred.def_id())
998 {
999 (expected_kind, "Async")
1000 } else {
1001 return None;
1002 };
1003
1004 let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() {
1005 ty::Closure(def_id, args) => {
1006 (def_id, args.as_closure().sig().map_bound(|sig| sig.inputs()[0]), false)
1007 }
1008 ty::CoroutineClosure(def_id, args) => (
1009 def_id,
1010 args.as_coroutine_closure()
1011 .coroutine_closure_sig()
1012 .map_bound(|sig| sig.tupled_inputs_ty),
1013 !args.as_coroutine_closure().tupled_upvars_ty().is_ty_var()
1014 && args.as_coroutine_closure().has_self_borrows(),
1015 ),
1016 _ => return None,
1017 };
1018
1019 let expected_args = trait_pred.map_bound(|trait_pred| trait_pred.trait_ref.args.type_at(1));
1020
1021 if self.enter_forall(found_args, |found_args| {
1024 self.enter_forall(expected_args, |expected_args| {
1025 !self.can_eq(obligation.param_env, expected_args, found_args)
1026 })
1027 }) {
1028 return None;
1029 }
1030
1031 if let Some(found_kind) = self.closure_kind(self_ty)
1032 && !found_kind.extends(expected_kind)
1033 {
1034 let mut err = self.report_closure_error(
1035 &obligation,
1036 closure_def_id,
1037 found_kind,
1038 expected_kind,
1039 trait_prefix,
1040 );
1041 self.note_obligation_cause(&mut err, &obligation);
1042 return Some(err.emit());
1043 }
1044
1045 if has_self_borrows && expected_kind != ty::ClosureKind::FnOnce {
1049 let coro_kind = match self
1050 .tcx
1051 .coroutine_kind(self.tcx.coroutine_for_closure(closure_def_id))
1052 .unwrap()
1053 {
1054 rustc_hir::CoroutineKind::Desugared(desugaring, _) => desugaring.to_string(),
1055 coro => coro.to_string(),
1056 };
1057 let mut err = self.dcx().create_err(CoroClosureNotFn {
1058 span: self.tcx.def_span(closure_def_id),
1059 kind: expected_kind.as_str(),
1060 coro_kind,
1061 });
1062 self.note_obligation_cause(&mut err, &obligation);
1063 return Some(err.emit());
1064 }
1065
1066 None
1067 }
1068
1069 fn fn_arg_obligation(
1070 &self,
1071 obligation: &PredicateObligation<'tcx>,
1072 ) -> Result<(), ErrorGuaranteed> {
1073 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1074 && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
1075 && let arg = arg.peel_borrows()
1076 && let hir::ExprKind::Path(hir::QPath::Resolved(
1077 None,
1078 hir::Path { res: hir::def::Res::Local(hir_id), .. },
1079 )) = arg.kind
1080 && let Node::Pat(pat) = self.tcx.hir_node(*hir_id)
1081 && let Some((preds, guar)) = self.reported_trait_errors.borrow().get(&pat.span)
1082 && preds.contains(&obligation.as_goal())
1083 {
1084 return Err(*guar);
1085 }
1086 Ok(())
1087 }
1088
1089 fn detect_negative_literal(
1090 &self,
1091 obligation: &PredicateObligation<'tcx>,
1092 trait_pred: ty::PolyTraitPredicate<'tcx>,
1093 err: &mut Diag<'_>,
1094 ) -> bool {
1095 if let ObligationCauseCode::UnOp { hir_id, .. } = obligation.cause.code()
1096 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1097 && let hir::ExprKind::Unary(hir::UnOp::Neg, inner) = expr.kind
1098 && let hir::ExprKind::Lit(lit) = inner.kind
1099 && let LitKind::Int(_, LitIntType::Unsuffixed) = lit.node
1100 {
1101 err.span_suggestion_verbose(
1102 lit.span.shrink_to_hi(),
1103 "consider specifying an integer type that can be negative",
1104 match trait_pred.skip_binder().self_ty().kind() {
1105 ty::Uint(ty::UintTy::Usize) => "isize",
1106 ty::Uint(ty::UintTy::U8) => "i8",
1107 ty::Uint(ty::UintTy::U16) => "i16",
1108 ty::Uint(ty::UintTy::U32) => "i32",
1109 ty::Uint(ty::UintTy::U64) => "i64",
1110 ty::Uint(ty::UintTy::U128) => "i128",
1111 _ => "i64",
1112 }
1113 .to_string(),
1114 Applicability::MaybeIncorrect,
1115 );
1116 return true;
1117 }
1118 false
1119 }
1120
1121 fn try_conversion_context(
1125 &self,
1126 obligation: &PredicateObligation<'tcx>,
1127 trait_pred: ty::PolyTraitPredicate<'tcx>,
1128 err: &mut Diag<'_>,
1129 ) -> (bool, bool) {
1130 let span = obligation.cause.span;
1131 struct FindMethodSubexprOfTry {
1133 search_span: Span,
1134 }
1135 impl<'v> Visitor<'v> for FindMethodSubexprOfTry {
1136 type Result = ControlFlow<&'v hir::Expr<'v>>;
1137 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
1138 if let hir::ExprKind::Match(expr, _arms, hir::MatchSource::TryDesugar(_)) = ex.kind
1139 && ex.span.with_lo(ex.span.hi() - BytePos(1)).source_equal(self.search_span)
1140 && let hir::ExprKind::Call(_, [expr, ..]) = expr.kind
1141 {
1142 ControlFlow::Break(expr)
1143 } else {
1144 hir::intravisit::walk_expr(self, ex)
1145 }
1146 }
1147 }
1148 let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_id);
1149 let Some(body_id) = self.tcx.hir_node(hir_id).body_id() else { return (false, false) };
1150 let ControlFlow::Break(expr) =
1151 (FindMethodSubexprOfTry { search_span: span }).visit_body(self.tcx.hir_body(body_id))
1152 else {
1153 return (false, false);
1154 };
1155 let Some(typeck) = &self.typeck_results else {
1156 return (false, false);
1157 };
1158 let ObligationCauseCode::QuestionMark = obligation.cause.code().peel_derives() else {
1159 return (false, false);
1160 };
1161 let self_ty = trait_pred.skip_binder().self_ty();
1162 let found_ty = trait_pred.skip_binder().trait_ref.args.get(1).and_then(|a| a.as_type());
1163 let noted_missing_impl =
1164 self.note_missing_impl_for_question_mark(err, self_ty, found_ty, trait_pred);
1165
1166 let mut prev_ty = self.resolve_vars_if_possible(
1167 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1168 );
1169
1170 let get_e_type = |prev_ty: Ty<'tcx>| -> Option<Ty<'tcx>> {
1174 let ty::Adt(def, args) = prev_ty.kind() else {
1175 return None;
1176 };
1177 let Some(arg) = args.get(1) else {
1178 return None;
1179 };
1180 if !self.tcx.is_diagnostic_item(sym::Result, def.did()) {
1181 return None;
1182 }
1183 arg.as_type()
1184 };
1185
1186 let mut suggested = false;
1187 let mut chain = ::alloc::vec::Vec::new()vec![];
1188
1189 let mut expr = expr;
1191 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
1192 expr = rcvr_expr;
1196 chain.push((span, prev_ty));
1197
1198 let next_ty = self.resolve_vars_if_possible(
1199 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1200 );
1201
1202 let is_diagnostic_item = |symbol: Symbol, ty: Ty<'tcx>| {
1203 let ty::Adt(def, _) = ty.kind() else {
1204 return false;
1205 };
1206 self.tcx.is_diagnostic_item(symbol, def.did())
1207 };
1208 if let Some(ty) = get_e_type(prev_ty)
1212 && let Some(found_ty) = found_ty
1213 && (
1218 ( path_segment.ident.name == sym::map_err
1220 && is_diagnostic_item(sym::Result, next_ty)
1221 ) || ( path_segment.ident.name == sym::ok_or_else
1223 && is_diagnostic_item(sym::Option, next_ty)
1224 )
1225 )
1226 && let ty::Tuple(tys) = found_ty.kind()
1228 && tys.is_empty()
1229 && self.can_eq(obligation.param_env, ty, found_ty)
1231 && let [arg] = args
1233 && let hir::ExprKind::Closure(closure) = arg.kind
1234 && let body = self.tcx.hir_body(closure.body)
1236 && let hir::ExprKind::Block(block, _) = body.value.kind
1237 && let None = block.expr
1238 && let [.., stmt] = block.stmts
1240 && let hir::StmtKind::Semi(expr) = stmt.kind
1241 && let expr_ty = self.resolve_vars_if_possible(
1242 typeck.expr_ty_adjusted_opt(expr)
1243 .unwrap_or(Ty::new_misc_error(self.tcx)),
1244 )
1245 && self
1246 .infcx
1247 .type_implements_trait(
1248 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1249 [self_ty, expr_ty],
1250 obligation.param_env,
1251 )
1252 .must_apply_modulo_regions()
1253 {
1254 suggested = true;
1255 err.span_suggestion_short(
1256 stmt.span.with_lo(expr.span.hi()),
1257 "remove this semicolon",
1258 String::new(),
1259 Applicability::MachineApplicable,
1260 );
1261 }
1262
1263 prev_ty = next_ty;
1264
1265 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1266 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
1267 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
1268 {
1269 let parent = self.tcx.parent_hir_node(binding.hir_id);
1270 if let hir::Node::LetStmt(local) = parent
1272 && let Some(binding_expr) = local.init
1273 {
1274 expr = binding_expr;
1276 }
1277 if let hir::Node::Param(_param) = parent {
1278 break;
1280 }
1281 }
1282 }
1283 prev_ty = self.resolve_vars_if_possible(
1287 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1288 );
1289 chain.push((expr.span, prev_ty));
1290
1291 let mut prev = None;
1292 let mut iter = chain.into_iter().rev().peekable();
1293 while let Some((span, err_ty)) = iter.next() {
1294 let is_last = iter.peek().is_none();
1295 let err_ty = get_e_type(err_ty);
1296 let err_ty = match (err_ty, prev) {
1297 (Some(err_ty), Some(prev)) if !self.can_eq(obligation.param_env, err_ty, prev) => {
1298 err_ty
1299 }
1300 (Some(err_ty), None) => err_ty,
1301 _ => {
1302 prev = err_ty;
1303 continue;
1304 }
1305 };
1306
1307 let implements_from = self
1308 .infcx
1309 .type_implements_trait(
1310 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1311 [self_ty, err_ty],
1312 obligation.param_env,
1313 )
1314 .must_apply_modulo_regions();
1315
1316 let err_ty_str = self.tcx.short_string(err_ty, err.long_ty_path());
1317 let label = if !implements_from && is_last {
1318 ::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!(
1319 "this can't be annotated with `?` because it has type `Result<_, {err_ty_str}>`"
1320 )
1321 } else {
1322 ::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}>`")
1323 };
1324
1325 if !suggested || !implements_from {
1326 err.span_label(span, label);
1327 }
1328 prev = Some(err_ty);
1329 }
1330 (suggested, noted_missing_impl)
1331 }
1332
1333 fn note_missing_impl_for_question_mark(
1334 &self,
1335 err: &mut Diag<'_>,
1336 self_ty: Ty<'_>,
1337 found_ty: Option<Ty<'_>>,
1338 trait_pred: ty::PolyTraitPredicate<'tcx>,
1339 ) -> bool {
1340 match (self_ty.kind(), found_ty) {
1341 (ty::Adt(def, _), Some(ty))
1342 if let ty::Adt(found, _) = ty.kind()
1343 && def.did().is_local()
1344 && found.did().is_local() =>
1345 {
1346 err.span_note(
1347 self.tcx.def_span(def.did()),
1348 ::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}>`"),
1349 );
1350 }
1351 (ty::Adt(def, _), None) if def.did().is_local() => {
1352 let trait_path = self.tcx.short_string(
1353 trait_pred.skip_binder().trait_ref.print_only_trait_path(),
1354 err.long_ty_path(),
1355 );
1356 err.span_note(
1357 self.tcx.def_span(def.did()),
1358 ::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}`"),
1359 );
1360 }
1361 (ty::Adt(def, _), Some(ty)) if def.did().is_local() => {
1362 err.span_note(
1363 self.tcx.def_span(def.did()),
1364 ::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}>`"),
1365 );
1366 }
1367 (_, Some(ty))
1368 if let ty::Adt(def, _) = ty.kind()
1369 && def.did().is_local() =>
1370 {
1371 err.span_note(
1372 self.tcx.def_span(def.did()),
1373 ::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}>`"),
1374 );
1375 }
1376 _ => return false,
1377 }
1378 true
1379 }
1380
1381 fn report_const_param_not_wf(
1382 &self,
1383 ty: Ty<'tcx>,
1384 obligation: &PredicateObligation<'tcx>,
1385 ) -> Diag<'a> {
1386 let def_id = obligation.cause.body_id;
1387 let span = self.tcx.ty_span(def_id);
1388
1389 let mut file = None;
1390 let ty_str = self.tcx.short_string(ty, &mut file);
1391 let mut diag = match ty.kind() {
1392 ty::Float(_) => {
1393 {
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!(
1394 self.dcx(),
1395 span,
1396 E0741,
1397 "`{ty_str}` is forbidden as the type of a const generic parameter",
1398 )
1399 }
1400 ty::FnPtr(..) => {
1401 {
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!(
1402 self.dcx(),
1403 span,
1404 E0741,
1405 "using function pointers as const generic parameters is forbidden",
1406 )
1407 }
1408 ty::RawPtr(_, _) => {
1409 {
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!(
1410 self.dcx(),
1411 span,
1412 E0741,
1413 "using raw pointers as const generic parameters is forbidden",
1414 )
1415 }
1416 ty::Adt(def, _) => {
1417 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!(
1419 self.dcx(),
1420 span,
1421 E0741,
1422 "`{ty_str}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
1423 );
1424 if let Some(span) = self.tcx.hir_span_if_local(def.did())
1427 && obligation.cause.code().parent().is_none()
1428 {
1429 if ty.is_structural_eq_shallow(self.tcx) {
1430 diag.span_suggestion(
1431 span.shrink_to_lo(),
1432 ::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()),
1433 "#[derive(ConstParamTy)]\n",
1434 Applicability::MachineApplicable,
1435 );
1436 } else {
1437 diag.span_suggestion(
1440 span.shrink_to_lo(),
1441 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {0}",
def.descr()))
})format!(
1442 "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {}",
1443 def.descr()
1444 ),
1445 "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1446 Applicability::MachineApplicable,
1447 );
1448 }
1449 }
1450 diag
1451 }
1452 _ => {
1453 {
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!(
1454 self.dcx(),
1455 span,
1456 E0741,
1457 "`{ty_str}` can't be used as a const parameter type",
1458 )
1459 }
1460 };
1461 diag.long_ty_path = file;
1462
1463 let mut code = obligation.cause.code();
1464 let mut pred = obligation.predicate.as_trait_clause();
1465 while let Some((next_code, next_pred)) = code.parent_with_predicate() {
1466 if let Some(pred) = pred {
1467 self.enter_forall(pred, |pred| {
1468 let ty = self.tcx.short_string(pred.self_ty(), diag.long_ty_path());
1469 let trait_path = self
1470 .tcx
1471 .short_string(pred.print_modifiers_and_trait_path(), diag.long_ty_path());
1472 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"));
1473 })
1474 }
1475 code = next_code;
1476 pred = next_pred;
1477 }
1478
1479 diag
1480 }
1481}
1482
1483impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
1484 fn can_match_trait(
1485 &self,
1486 param_env: ty::ParamEnv<'tcx>,
1487 goal: ty::TraitPredicate<'tcx>,
1488 assumption: ty::PolyTraitPredicate<'tcx>,
1489 ) -> bool {
1490 if goal.polarity != assumption.polarity() {
1492 return false;
1493 }
1494
1495 let trait_assumption = self.instantiate_binder_with_fresh_vars(
1496 DUMMY_SP,
1497 infer::BoundRegionConversionTime::HigherRankedType,
1498 assumption,
1499 );
1500
1501 self.can_eq(param_env, goal.trait_ref, trait_assumption.trait_ref)
1502 }
1503
1504 fn can_match_host_effect(
1505 &self,
1506 param_env: ty::ParamEnv<'tcx>,
1507 goal: ty::HostEffectPredicate<'tcx>,
1508 assumption: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
1509 ) -> bool {
1510 let assumption = self.instantiate_binder_with_fresh_vars(
1511 DUMMY_SP,
1512 infer::BoundRegionConversionTime::HigherRankedType,
1513 assumption,
1514 );
1515
1516 assumption.constness.satisfies(goal.constness)
1517 && self.can_eq(param_env, goal.trait_ref, assumption.trait_ref)
1518 }
1519
1520 fn as_host_effect_clause(
1521 predicate: ty::Predicate<'tcx>,
1522 ) -> Option<ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>> {
1523 predicate.as_clause().and_then(|clause| match clause.kind().skip_binder() {
1524 ty::ClauseKind::HostEffect(pred) => Some(clause.kind().rebind(pred)),
1525 _ => None,
1526 })
1527 }
1528
1529 fn can_match_projection(
1530 &self,
1531 param_env: ty::ParamEnv<'tcx>,
1532 goal: ty::ProjectionPredicate<'tcx>,
1533 assumption: ty::PolyProjectionPredicate<'tcx>,
1534 ) -> bool {
1535 let assumption = self.instantiate_binder_with_fresh_vars(
1536 DUMMY_SP,
1537 infer::BoundRegionConversionTime::HigherRankedType,
1538 assumption,
1539 );
1540
1541 self.can_eq(param_env, goal.projection_term, assumption.projection_term)
1542 && self.can_eq(param_env, goal.term, assumption.term)
1543 }
1544
1545 x;#[instrument(level = "debug", skip(self), ret)]
1548 pub(super) fn error_implies(
1549 &self,
1550 cond: Goal<'tcx, ty::Predicate<'tcx>>,
1551 error: Goal<'tcx, ty::Predicate<'tcx>>,
1552 ) -> bool {
1553 if cond == error {
1554 return true;
1555 }
1556
1557 if cond.param_env != error.param_env {
1561 return false;
1562 }
1563 let param_env = error.param_env;
1564
1565 if let Some(error) = error.predicate.as_trait_clause() {
1566 self.enter_forall(error, |error| {
1567 elaborate(self.tcx, std::iter::once(cond.predicate))
1568 .filter_map(|implied| implied.as_trait_clause())
1569 .any(|implied| self.can_match_trait(param_env, error, implied))
1570 })
1571 } else if let Some(error) = Self::as_host_effect_clause(error.predicate) {
1572 self.enter_forall(error, |error| {
1573 elaborate(self.tcx, std::iter::once(cond.predicate))
1574 .filter_map(Self::as_host_effect_clause)
1575 .any(|implied| self.can_match_host_effect(param_env, error, implied))
1576 })
1577 } else if let Some(error) = error.predicate.as_projection_clause() {
1578 self.enter_forall(error, |error| {
1579 elaborate(self.tcx, std::iter::once(cond.predicate))
1580 .filter_map(|implied| implied.as_projection_clause())
1581 .any(|implied| self.can_match_projection(param_env, error, implied))
1582 })
1583 } else {
1584 false
1585 }
1586 }
1587
1588 #[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(1588u32),
::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);
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) }
}
ty::PredicateKind::AliasRelate(lhs, rhs, _) => {
let derive_better_type_error =
|alias_term: ty::AliasTerm<'tcx>,
expected_term: ty::Term<'tcx>|
{
let ocx = ObligationCtxt::new(self);
let normalized_term =
ocx.normalize(&ObligationCause::dummy(),
obligation.param_env,
Unnormalized::new_wip(alias_term.to_term(self.tcx)));
if let Err(terr) =
ocx.eq(&ObligationCause::dummy(), obligation.param_env,
expected_term, normalized_term) {
Some((terr, self.resolve_vars_if_possible(normalized_term)))
} else { None }
};
if let Some(lhs) = lhs.to_alias_term() &&
let ty::AliasTermKind::ProjectionTy { .. } |
ty::AliasTermKind::ProjectionConst { .. } = lhs.kind &&
let Some((better_type_err, expected_term)) =
derive_better_type_error(lhs, rhs) {
(Some((lhs, self.resolve_vars_if_possible(expected_term),
rhs)), better_type_err)
} else if let Some(rhs) = rhs.to_alias_term() &&
let ty::AliasTermKind::ProjectionTy { .. } |
ty::AliasTermKind::ProjectionConst { .. } = rhs.kind &&
let Some((better_type_err, expected_term)) =
derive_better_type_error(rhs, lhs) {
(Some((rhs, self.resolve_vars_if_possible(expected_term),
lhs)), better_type_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; };
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)]
1589 pub(super) fn report_projection_error(
1590 &self,
1591 obligation: &PredicateObligation<'tcx>,
1592 error: &MismatchedProjectionTypes<'tcx>,
1593 ) -> ErrorGuaranteed {
1594 let predicate = self.resolve_vars_if_possible(obligation.predicate);
1595
1596 if let Err(e) = predicate.error_reported() {
1597 return e;
1598 }
1599
1600 self.probe(|_| {
1601 let bound_predicate = predicate.kind();
1606 let (values, err) = match bound_predicate.skip_binder() {
1607 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
1608 let ocx = ObligationCtxt::new(self);
1609
1610 let data = self.instantiate_binder_with_fresh_vars(
1611 obligation.cause.span,
1612 infer::BoundRegionConversionTime::HigherRankedType,
1613 bound_predicate.rebind(data),
1614 );
1615 let unnormalized_term = data.projection_term.to_term(self.tcx);
1616 let normalized_term = ocx.normalize(
1619 &obligation.cause,
1620 obligation.param_env,
1621 Unnormalized::new_wip(unnormalized_term),
1622 );
1623
1624 let _ = ocx.try_evaluate_obligations();
1630
1631 if let Err(new_err) =
1632 ocx.eq(&obligation.cause, obligation.param_env, data.term, normalized_term)
1633 {
1634 (
1635 Some((
1636 data.projection_term,
1637 self.resolve_vars_if_possible(normalized_term),
1638 data.term,
1639 )),
1640 new_err,
1641 )
1642 } else {
1643 (None, error.err)
1644 }
1645 }
1646 ty::PredicateKind::AliasRelate(lhs, rhs, _) => {
1647 let derive_better_type_error =
1648 |alias_term: ty::AliasTerm<'tcx>, expected_term: ty::Term<'tcx>| {
1649 let ocx = ObligationCtxt::new(self);
1650
1651 let normalized_term = ocx.normalize(
1652 &ObligationCause::dummy(),
1653 obligation.param_env,
1654 Unnormalized::new_wip(alias_term.to_term(self.tcx)),
1655 );
1656
1657 if let Err(terr) = ocx.eq(
1658 &ObligationCause::dummy(),
1659 obligation.param_env,
1660 expected_term,
1661 normalized_term,
1662 ) {
1663 Some((terr, self.resolve_vars_if_possible(normalized_term)))
1664 } else {
1665 None
1666 }
1667 };
1668
1669 if let Some(lhs) = lhs.to_alias_term()
1670 && let ty::AliasTermKind::ProjectionTy { .. }
1671 | ty::AliasTermKind::ProjectionConst { .. } = lhs.kind
1672 && let Some((better_type_err, expected_term)) =
1673 derive_better_type_error(lhs, rhs)
1674 {
1675 (
1676 Some((lhs, self.resolve_vars_if_possible(expected_term), rhs)),
1677 better_type_err,
1678 )
1679 } else if let Some(rhs) = rhs.to_alias_term()
1680 && let ty::AliasTermKind::ProjectionTy { .. }
1681 | ty::AliasTermKind::ProjectionConst { .. } = rhs.kind
1682 && let Some((better_type_err, expected_term)) =
1683 derive_better_type_error(rhs, lhs)
1684 {
1685 (
1686 Some((rhs, self.resolve_vars_if_possible(expected_term), lhs)),
1687 better_type_err,
1688 )
1689 } else {
1690 (None, error.err)
1691 }
1692 }
1693 _ => (None, error.err),
1694 };
1695
1696 let mut file = None;
1697 let (msg, span, closure_span) = values
1698 .and_then(|(predicate, normalized_term, expected_term)| {
1699 self.maybe_detailed_projection_msg(
1700 obligation.cause.span,
1701 predicate,
1702 normalized_term,
1703 expected_term,
1704 &mut file,
1705 )
1706 })
1707 .unwrap_or_else(|| {
1708 (
1709 with_forced_trimmed_paths!(format!(
1710 "type mismatch resolving `{}`",
1711 self.tcx
1712 .short_string(self.resolve_vars_if_possible(predicate), &mut file),
1713 )),
1714 obligation.cause.span,
1715 None,
1716 )
1717 });
1718 let mut diag = struct_span_code_err!(self.dcx(), span, E0271, "{msg}");
1719 *diag.long_ty_path() = file;
1720 if let Some(span) = closure_span {
1721 diag.span_label(span, "this closure");
1738 if !span.overlaps(obligation.cause.span) {
1739 diag.span_label(obligation.cause.span, "closure used here");
1741 }
1742 }
1743
1744 let secondary_span = self.probe(|_| {
1745 let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1746 predicate.kind().skip_binder()
1747 else {
1748 return None;
1749 };
1750
1751 let trait_ref = self.enter_forall_and_leak_universe(
1752 predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)),
1753 );
1754 let Ok(Some(ImplSource::UserDefined(impl_data))) =
1755 SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref))
1756 else {
1757 return None;
1758 };
1759
1760 let Ok(node) =
1761 specialization_graph::assoc_def(self.tcx, impl_data.impl_def_id, proj.def_id())
1762 else {
1763 return None;
1764 };
1765
1766 if !node.is_final() {
1767 return None;
1768 }
1769
1770 match self.tcx.hir_get_if_local(node.item.def_id) {
1771 Some(
1772 hir::Node::TraitItem(hir::TraitItem {
1773 kind: hir::TraitItemKind::Type(_, Some(ty)),
1774 ..
1775 })
1776 | hir::Node::ImplItem(hir::ImplItem {
1777 kind: hir::ImplItemKind::Type(ty),
1778 ..
1779 }),
1780 ) => Some((
1781 ty.span,
1782 with_forced_trimmed_paths!(Cow::from(format!(
1783 "type mismatch resolving `{}`",
1784 self.tcx.short_string(
1785 self.resolve_vars_if_possible(predicate),
1786 diag.long_ty_path()
1787 ),
1788 ))),
1789 true,
1790 )),
1791 _ => None,
1792 }
1793 });
1794
1795 self.note_type_err(
1796 &mut diag,
1797 &obligation.cause,
1798 secondary_span,
1799 values.map(|(_, normalized_ty, expected_ty)| {
1800 obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(
1801 expected_ty,
1802 normalized_ty,
1803 )))
1804 }),
1805 err,
1806 false,
1807 Some(span),
1808 );
1809 self.note_obligation_cause(&mut diag, obligation);
1810 diag.emit()
1811 })
1812 }
1813
1814 fn maybe_detailed_projection_msg(
1815 &self,
1816 mut span: Span,
1817 projection_term: ty::AliasTerm<'tcx>,
1818 normalized_ty: ty::Term<'tcx>,
1819 expected_ty: ty::Term<'tcx>,
1820 long_ty_path: &mut Option<PathBuf>,
1821 ) -> Option<(String, Span, Option<Span>)> {
1822 let projection_def_id = projection_term.expect_projection_def_id();
1823 let trait_def_id = projection_term.trait_def_id(self.tcx);
1824 let self_ty = projection_term.self_ty();
1825
1826 {
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! {
1827 if self.tcx.is_lang_item(projection_def_id, LangItem::FnOnceOutput) {
1828 let (span, closure_span) = if let ty::Closure(def_id, _) = *self_ty.kind() {
1829 let def_span = self.tcx.def_span(def_id);
1830 if let Some(local_def_id) = def_id.as_local()
1831 && let node = self.tcx.hir_node_by_def_id(local_def_id)
1832 && let Some(fn_decl) = node.fn_decl()
1833 && let Some(id) = node.body_id()
1834 {
1835 span = match fn_decl.output {
1836 hir::FnRetTy::Return(ty) => ty.span,
1837 hir::FnRetTy::DefaultReturn(_) => {
1838 let body = self.tcx.hir_body(id);
1839 match body.value.kind {
1840 hir::ExprKind::Block(
1841 hir::Block { expr: Some(expr), .. },
1842 _,
1843 ) => expr.span,
1844 hir::ExprKind::Block(
1845 hir::Block {
1846 expr: None, stmts: [.., last], ..
1847 },
1848 _,
1849 ) => last.span,
1850 _ => body.value.span,
1851 }
1852 }
1853 };
1854 }
1855 (span, Some(def_span))
1856 } else {
1857 (span, None)
1858 };
1859 let item = match self_ty.kind() {
1860 ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
1861 _ => self.tcx.short_string(self_ty, long_ty_path),
1862 };
1863 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1864 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1865 Some((format!(
1866 "expected `{item}` to return `{expected_ty}`, but it returns `{normalized_ty}`",
1867 ), span, closure_span))
1868 } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
1869 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1870 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1871 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1872 Some((format!(
1873 "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
1874 resolves to `{normalized_ty}`"
1875 ), span, None))
1876 } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
1877 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1878 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1879 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1880 Some((format!(
1881 "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
1882 yields `{normalized_ty}`"
1883 ), span, None))
1884 } else {
1885 None
1886 }
1887 }
1888 }
1889
1890 pub fn fuzzy_match_tys(
1891 &self,
1892 mut a: Ty<'tcx>,
1893 mut b: Ty<'tcx>,
1894 ignoring_lifetimes: bool,
1895 ) -> Option<CandidateSimilarity> {
1896 fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
1899 match t.kind() {
1900 ty::Bool => Some(0),
1901 ty::Char => Some(1),
1902 ty::Str => Some(2),
1903 ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => Some(2),
1904 ty::Int(..)
1905 | ty::Uint(..)
1906 | ty::Float(..)
1907 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
1908 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1909 ty::Array(..) | ty::Slice(..) => Some(6),
1910 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1911 ty::Dynamic(..) => Some(8),
1912 ty::Closure(..) => Some(9),
1913 ty::Tuple(..) => Some(10),
1914 ty::Param(..) => Some(11),
1915 ty::Alias(ty::AliasTy { kind: ty::Projection { .. }, .. }) => Some(12),
1916 ty::Alias(ty::AliasTy { kind: ty::Inherent { .. }, .. }) => Some(13),
1917 ty::Alias(ty::AliasTy { kind: ty::Opaque { .. }, .. }) => Some(14),
1918 ty::Alias(ty::AliasTy { kind: ty::Free { .. }, .. }) => Some(15),
1919 ty::Never => Some(16),
1920 ty::Adt(..) => Some(17),
1921 ty::Coroutine(..) => Some(18),
1922 ty::Foreign(..) => Some(19),
1923 ty::CoroutineWitness(..) => Some(20),
1924 ty::CoroutineClosure(..) => Some(21),
1925 ty::Pat(..) => Some(22),
1926 ty::UnsafeBinder(..) => Some(23),
1927 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1928 }
1929 }
1930
1931 let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
1932 loop {
1933 match t.kind() {
1934 ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => t = *inner,
1935 _ => break t,
1936 }
1937 }
1938 };
1939
1940 if !ignoring_lifetimes {
1941 a = strip_references(a);
1942 b = strip_references(b);
1943 }
1944
1945 let cat_a = type_category(self.tcx, a)?;
1946 let cat_b = type_category(self.tcx, b)?;
1947 if a == b {
1948 Some(CandidateSimilarity::Exact { ignoring_lifetimes })
1949 } else if cat_a == cat_b {
1950 match (a.kind(), b.kind()) {
1951 (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
1952 (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
1953 (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
1959 self.fuzzy_match_tys(a, b, true).is_some()
1960 }
1961 _ => true,
1962 }
1963 .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
1964 } else if ignoring_lifetimes {
1965 None
1966 } else {
1967 self.fuzzy_match_tys(a, b, true)
1968 }
1969 }
1970
1971 pub(super) fn describe_closure(&self, kind: hir::ClosureKind) -> &'static str {
1972 match kind {
1973 hir::ClosureKind::Closure => "a closure",
1974 hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => "a coroutine",
1975 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1976 hir::CoroutineDesugaring::Async,
1977 hir::CoroutineSource::Block,
1978 )) => "an async block",
1979 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1980 hir::CoroutineDesugaring::Async,
1981 hir::CoroutineSource::Fn,
1982 )) => "an async function",
1983 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1984 hir::CoroutineDesugaring::Async,
1985 hir::CoroutineSource::Closure,
1986 ))
1987 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
1988 "an async closure"
1989 }
1990 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1991 hir::CoroutineDesugaring::AsyncGen,
1992 hir::CoroutineSource::Block,
1993 )) => "an async gen block",
1994 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1995 hir::CoroutineDesugaring::AsyncGen,
1996 hir::CoroutineSource::Fn,
1997 )) => "an async gen function",
1998 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1999 hir::CoroutineDesugaring::AsyncGen,
2000 hir::CoroutineSource::Closure,
2001 ))
2002 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
2003 "an async gen closure"
2004 }
2005 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2006 hir::CoroutineDesugaring::Gen,
2007 hir::CoroutineSource::Block,
2008 )) => "a gen block",
2009 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2010 hir::CoroutineDesugaring::Gen,
2011 hir::CoroutineSource::Fn,
2012 )) => "a gen function",
2013 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2014 hir::CoroutineDesugaring::Gen,
2015 hir::CoroutineSource::Closure,
2016 ))
2017 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => "a gen closure",
2018 }
2019 }
2020
2021 pub(super) fn find_similar_impl_candidates(
2022 &self,
2023 trait_pred: ty::PolyTraitPredicate<'tcx>,
2024 ) -> Vec<ImplCandidate<'tcx>> {
2025 let mut candidates: Vec<_> = self
2026 .tcx
2027 .all_impls(trait_pred.def_id())
2028 .filter_map(|def_id| {
2029 let imp = self.tcx.impl_trait_header(def_id);
2030 if imp.polarity != ty::ImplPolarity::Positive
2031 || !self.tcx.is_user_visible_dep(def_id.krate)
2032 {
2033 return None;
2034 }
2035 let imp = imp.trait_ref.skip_binder();
2036
2037 self.fuzzy_match_tys(trait_pred.skip_binder().self_ty(), imp.self_ty(), false).map(
2038 |similarity| ImplCandidate { trait_ref: imp, similarity, impl_def_id: def_id },
2039 )
2040 })
2041 .collect();
2042 if candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
2043 candidates.retain(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. }));
2047 }
2048 candidates
2049 }
2050
2051 pub(super) fn report_similar_impl_candidates(
2052 &self,
2053 impl_candidates: &[ImplCandidate<'tcx>],
2054 obligation: &PredicateObligation<'tcx>,
2055 trait_pred: ty::PolyTraitPredicate<'tcx>,
2056 body_def_id: LocalDefId,
2057 err: &mut Diag<'_>,
2058 other: bool,
2059 param_env: ty::ParamEnv<'tcx>,
2060 ) -> bool {
2061 let parent_map = self.tcx.visible_parent_map(());
2062 let alternative_candidates = |def_id: DefId| {
2063 let mut impl_candidates: Vec<_> = self
2064 .tcx
2065 .all_impls(def_id)
2066 .filter(|def_id| !self.tcx.do_not_recommend_impl(*def_id))
2068 .map(|def_id| (self.tcx.impl_trait_header(def_id), def_id))
2070 .filter_map(|(header, def_id)| {
2071 (header.polarity == ty::ImplPolarity::Positive
2072 || self.tcx.is_automatically_derived(def_id))
2073 .then(|| (header.trait_ref.instantiate_identity().skip_norm_wip(), def_id))
2074 })
2075 .filter(|(trait_ref, _)| {
2076 let self_ty = trait_ref.self_ty();
2077 if let ty::Param(_) = self_ty.kind() {
2079 false
2080 }
2081 else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
2083 let mut did = def.did();
2087 if self.tcx.visibility(did).is_accessible_from(body_def_id, self.tcx) {
2088 if !did.is_local() {
2090 let mut previously_seen_dids: FxHashSet<DefId> = Default::default();
2091 previously_seen_dids.insert(did);
2092 while let Some(&parent) = parent_map.get(&did)
2093 && let hash_set::Entry::Vacant(v) =
2094 previously_seen_dids.entry(parent)
2095 {
2096 if self.tcx.is_doc_hidden(did) {
2097 return false;
2098 }
2099 v.insert();
2100 did = parent;
2101 }
2102 }
2103 true
2104 } else {
2105 false
2106 }
2107 } else {
2108 true
2109 }
2110 })
2111 .collect();
2112
2113 impl_candidates.sort_by_key(|(tr, _)| tr.to_string());
2114 impl_candidates.dedup();
2115 impl_candidates
2116 };
2117
2118 if let [single] = &impl_candidates {
2119 let self_ty = trait_pred.skip_binder().self_ty();
2120 if !self_ty.has_escaping_bound_vars() {
2121 let self_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
2122 if let ty::Ref(_, inner_ty, _) = self_ty.kind()
2123 && self.can_eq(param_env, single.trait_ref.self_ty(), *inner_ty)
2124 && !self.where_clause_expr_matches_failed_self_ty(obligation, self_ty)
2125 {
2126 return true;
2130 }
2131 }
2132
2133 if self.probe(|_| {
2136 let ocx = ObligationCtxt::new(self);
2137
2138 self.enter_forall(trait_pred, |obligation_trait_ref| {
2139 let impl_args = self.fresh_args_for_item(DUMMY_SP, single.impl_def_id);
2140 let impl_trait_ref = ocx.normalize(
2141 &ObligationCause::dummy(),
2142 param_env,
2143 ty::EarlyBinder::bind(single.trait_ref).instantiate(self.tcx, impl_args),
2144 );
2145
2146 ocx.register_obligations(
2147 self.tcx
2148 .predicates_of(single.impl_def_id)
2149 .instantiate(self.tcx, impl_args)
2150 .into_iter()
2151 .map(|(clause, _)| {
2152 Obligation::new(
2153 self.tcx,
2154 ObligationCause::dummy(),
2155 param_env,
2156 clause.skip_norm_wip(),
2157 )
2158 }),
2159 );
2160 if !ocx.try_evaluate_obligations().is_empty() {
2161 return false;
2162 }
2163
2164 let mut terrs = ::alloc::vec::Vec::new()vec![];
2165 for (obligation_arg, impl_arg) in
2166 std::iter::zip(obligation_trait_ref.trait_ref.args, impl_trait_ref.args)
2167 {
2168 if (obligation_arg, impl_arg).references_error() {
2169 return false;
2170 }
2171 if let Err(terr) =
2172 ocx.eq(&ObligationCause::dummy(), param_env, impl_arg, obligation_arg)
2173 {
2174 terrs.push(terr);
2175 }
2176 if !ocx.try_evaluate_obligations().is_empty() {
2177 return false;
2178 }
2179 }
2180
2181 if terrs.len() == impl_trait_ref.args.len() {
2183 return false;
2184 }
2185
2186 let impl_trait_ref = self.resolve_vars_if_possible(impl_trait_ref);
2187 if impl_trait_ref.references_error() {
2188 return false;
2189 }
2190
2191 if let [child, ..] = &err.children[..]
2192 && child.level == Level::Help
2193 && let Some(line) = child.messages.get(0)
2194 && let Some(line) = line.0.as_str()
2195 && line.starts_with("the trait")
2196 && line.contains("is not implemented for")
2197 {
2198 err.children.remove(0);
2205 }
2206
2207 let traits = self.cmp_traits(
2208 obligation_trait_ref.def_id(),
2209 &obligation_trait_ref.trait_ref.args[1..],
2210 impl_trait_ref.def_id,
2211 &impl_trait_ref.args[1..],
2212 );
2213 let traits_content = (traits.0.content(), traits.1.content());
2214 let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty());
2215 let types_content = (types.0.content(), types.1.content());
2216 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 `")];
2217 if traits_content.0 == traits_content.1 {
2218 msg.push(StringPart::normal(
2219 impl_trait_ref.print_trait_sugared().to_string(),
2220 ));
2221 } else {
2222 msg.extend(traits.0.0);
2223 }
2224 msg.extend([
2225 StringPart::normal("` "),
2226 StringPart::highlighted("is not"),
2227 StringPart::normal(" implemented for `"),
2228 ]);
2229 if types_content.0 == types_content.1 {
2230 let ty = self
2231 .tcx
2232 .short_string(obligation_trait_ref.self_ty(), err.long_ty_path());
2233 msg.push(StringPart::normal(ty));
2234 } else {
2235 msg.extend(types.0.0);
2236 }
2237 msg.push(StringPart::normal("`"));
2238 if types_content.0 == types_content.1 {
2239 msg.push(StringPart::normal("\nbut trait `"));
2240 msg.extend(traits.1.0);
2241 msg.extend([
2242 StringPart::normal("` "),
2243 StringPart::highlighted("is"),
2244 StringPart::normal(" implemented for it"),
2245 ]);
2246 } else if traits_content.0 == traits_content.1 {
2247 msg.extend([
2248 StringPart::normal("\nbut it "),
2249 StringPart::highlighted("is"),
2250 StringPart::normal(" implemented for `"),
2251 ]);
2252 msg.extend(types.1.0);
2253 msg.push(StringPart::normal("`"));
2254 } else {
2255 msg.push(StringPart::normal("\nbut trait `"));
2256 msg.extend(traits.1.0);
2257 msg.extend([
2258 StringPart::normal("` "),
2259 StringPart::highlighted("is"),
2260 StringPart::normal(" implemented for `"),
2261 ]);
2262 msg.extend(types.1.0);
2263 msg.push(StringPart::normal("`"));
2264 }
2265 err.highlighted_span_help(self.tcx.def_span(single.impl_def_id), msg);
2266
2267 if let [TypeError::Sorts(exp_found)] = &terrs[..] {
2268 let exp_found = self.resolve_vars_if_possible(*exp_found);
2269 let expected =
2270 self.tcx.short_string(exp_found.expected, err.long_ty_path());
2271 let found = self.tcx.short_string(exp_found.found, err.long_ty_path());
2272 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![
2273 StringPart::normal("for that trait implementation, "),
2274 StringPart::normal("expected `"),
2275 StringPart::highlighted(expected),
2276 StringPart::normal("`, found `"),
2277 StringPart::highlighted(found),
2278 StringPart::normal("`"),
2279 ]);
2280 self.suggest_function_pointers_impl(None, &exp_found, err);
2281 }
2282
2283 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2284 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2285 && !crates.is_empty()
2286 {
2287 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2288 err.help("you can use `cargo tree` to explore your dependency tree");
2289 }
2290 true
2291 })
2292 }) {
2293 return true;
2294 }
2295 }
2296
2297 let other = if other { "other " } else { "" };
2298 let report = |mut candidates: Vec<(TraitRef<'tcx>, DefId)>, err: &mut Diag<'_>| {
2299 candidates.retain(|(tr, _)| !tr.references_error());
2300 if candidates.is_empty() {
2301 return false;
2302 }
2303 let mut specific_candidates = candidates.clone();
2304 specific_candidates.retain(|(tr, _)| {
2305 tr.with_replaced_self_ty(self.tcx, trait_pred.skip_binder().self_ty())
2306 == trait_pred.skip_binder().trait_ref
2307 });
2308 if !specific_candidates.is_empty() {
2309 candidates = specific_candidates;
2312 }
2313 if let &[(cand, def_id)] = &candidates[..] {
2314 if self.tcx.is_diagnostic_item(sym::FromResidual, cand.def_id)
2315 && !self.tcx.features().enabled(sym::try_trait_v2)
2316 {
2317 return false;
2318 }
2319 let (desc, mention_castable) =
2320 match (cand.self_ty().kind(), trait_pred.self_ty().skip_binder().kind()) {
2321 (ty::FnPtr(..), ty::FnDef(..)) => {
2322 (" implemented for fn pointer `", ", cast using `as`")
2323 }
2324 (ty::FnPtr(..), _) => (" implemented for fn pointer `", ""),
2325 _ => (" implemented for `", ""),
2326 };
2327 let trait_ = self.tcx.short_string(cand.print_trait_sugared(), err.long_ty_path());
2328 let self_ty = self.tcx.short_string(cand.self_ty(), err.long_ty_path());
2329 err.highlighted_span_help(
2330 self.tcx.def_span(def_id),
2331 ::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![
2332 StringPart::normal(format!("the trait `{trait_}` ")),
2333 StringPart::highlighted("is"),
2334 StringPart::normal(desc),
2335 StringPart::highlighted(self_ty),
2336 StringPart::normal("`"),
2337 StringPart::normal(mention_castable),
2338 ],
2339 );
2340 return true;
2341 }
2342 let trait_ref = TraitRef::identity(self.tcx, candidates[0].0.def_id);
2343 let mut traits: Vec<_> =
2345 candidates.iter().map(|(c, _)| c.print_only_trait_path().to_string()).collect();
2346 traits.sort();
2347 traits.dedup();
2348 let all_traits_equal = traits.len() == 1;
2351 let mut types: Vec<_> =
2352 candidates.iter().map(|(c, _)| c.self_ty().to_string()).collect();
2353 types.sort();
2354 types.dedup();
2355 let all_types_equal = types.len() == 1;
2356
2357 let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose {
2358 candidates.len()
2359 } else {
2360 8
2361 };
2362 if candidates.len() < 5 {
2363 let spans: Vec<_> =
2364 candidates.iter().map(|&(_, def_id)| self.tcx.def_span(def_id)).collect();
2365 let mut span: MultiSpan = spans.into();
2366 for (c, def_id) in &candidates {
2367 let msg = if all_traits_equal {
2368 ::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()))
2369 } else if all_types_equal {
2370 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2371 "`{}`",
2372 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path())
2373 )
2374 } else {
2375 ::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!(
2376 "`{}` implements `{}`",
2377 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2378 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path()),
2379 )
2380 };
2381 span.push_span_label(self.tcx.def_span(*def_id), msg);
2382 }
2383 let msg = if all_types_equal {
2384 ::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!(
2385 "`{}` implements trait `{}`",
2386 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2387 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2388 )
2389 } else {
2390 ::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!(
2391 "the following {other}types implement trait `{}`",
2392 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2393 )
2394 };
2395 err.span_help(span, msg);
2396 } else {
2397 let candidate_names: Vec<String> = candidates
2398 .iter()
2399 .map(|(c, _)| {
2400 if all_traits_equal {
2401 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n {0}",
self.tcx.short_string(c.self_ty(), err.long_ty_path())))
})format!(
2402 "\n {}",
2403 self.tcx.short_string(c.self_ty(), err.long_ty_path())
2404 )
2405 } else if all_types_equal {
2406 ::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!(
2407 "\n {}",
2408 self.tcx
2409 .short_string(c.print_only_trait_path(), err.long_ty_path())
2410 )
2411 } else {
2412 ::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!(
2413 "\n `{}` implements `{}`",
2414 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2415 self.tcx
2416 .short_string(c.print_only_trait_path(), err.long_ty_path()),
2417 )
2418 }
2419 })
2420 .collect();
2421 let msg = if all_types_equal {
2422 ::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!(
2423 "`{}` implements trait `{}`",
2424 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2425 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2426 )
2427 } else {
2428 ::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!(
2429 "the following {other}types implement trait `{}`",
2430 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2431 )
2432 };
2433
2434 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!(
2435 "{msg}:{}{}",
2436 candidate_names[..end].join(""),
2437 if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
2438 format!("\nand {} others", candidates.len() - 8)
2439 } else {
2440 String::new()
2441 }
2442 ));
2443 }
2444
2445 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2446 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2447 && !crates.is_empty()
2448 {
2449 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2450 err.help("you can use `cargo tree` to explore your dependency tree");
2451 }
2452 true
2453 };
2454
2455 let impl_candidates = impl_candidates
2458 .into_iter()
2459 .cloned()
2460 .filter(|cand| !self.tcx.do_not_recommend_impl(cand.impl_def_id))
2461 .collect::<Vec<_>>();
2462
2463 let def_id = trait_pred.def_id();
2464 if impl_candidates.is_empty() {
2465 if self.tcx.trait_is_auto(def_id)
2466 || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2467 || self.tcx.get_diagnostic_name(def_id).is_some()
2468 {
2469 return false;
2471 }
2472 return report(alternative_candidates(def_id), err);
2473 }
2474
2475 let mut impl_candidates: Vec<_> = impl_candidates
2482 .iter()
2483 .cloned()
2484 .filter(|cand| !cand.trait_ref.references_error())
2485 .map(|mut cand| {
2486 cand.trait_ref = self
2490 .tcx
2491 .try_normalize_erasing_regions(
2492 ty::TypingEnv::non_body_analysis(self.tcx, cand.impl_def_id),
2493 Unnormalized::new_wip(cand.trait_ref),
2494 )
2495 .unwrap_or(cand.trait_ref);
2496 cand
2497 })
2498 .collect();
2499 impl_candidates.sort_by_key(|cand| {
2500 let len = if let GenericArgKind::Type(ty) = cand.trait_ref.args[0].kind()
2502 && let ty::Array(_, len) = ty.kind()
2503 {
2504 len.try_to_target_usize(self.tcx).unwrap_or(u64::MAX)
2506 } else {
2507 0
2508 };
2509
2510 (cand.similarity, len, cand.trait_ref.to_string())
2511 });
2512 let mut impl_candidates: Vec<_> =
2513 impl_candidates.into_iter().map(|cand| (cand.trait_ref, cand.impl_def_id)).collect();
2514 impl_candidates.dedup();
2515
2516 report(impl_candidates, err)
2517 }
2518
2519 fn report_similar_impl_candidates_for_root_obligation(
2520 &self,
2521 obligation: &PredicateObligation<'tcx>,
2522 trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2523 body_def_id: LocalDefId,
2524 err: &mut Diag<'_>,
2525 ) {
2526 let mut code = obligation.cause.code();
2533 let mut trait_pred = trait_predicate;
2534 let mut peeled = false;
2535 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
2536 code = parent_code;
2537 if let Some(parent_trait_pred) = parent_trait_pred {
2538 trait_pred = parent_trait_pred;
2539 peeled = true;
2540 }
2541 }
2542 let def_id = trait_pred.def_id();
2543 if peeled && !self.tcx.trait_is_auto(def_id) && self.tcx.as_lang_item(def_id).is_none() {
2549 let impl_candidates = self.find_similar_impl_candidates(trait_pred);
2550 self.report_similar_impl_candidates(
2551 &impl_candidates,
2552 obligation,
2553 trait_pred,
2554 body_def_id,
2555 err,
2556 true,
2557 obligation.param_env,
2558 );
2559 }
2560 }
2561
2562 fn get_parent_trait_ref(
2564 &self,
2565 code: &ObligationCauseCode<'tcx>,
2566 ) -> Option<(Ty<'tcx>, Option<Span>)> {
2567 match code {
2568 ObligationCauseCode::BuiltinDerived(data) => {
2569 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2570 match self.get_parent_trait_ref(&data.parent_code) {
2571 Some(t) => Some(t),
2572 None => {
2573 let ty = parent_trait_ref.skip_binder().self_ty();
2574 let span = TyCategory::from_ty(self.tcx, ty)
2575 .map(|(_, def_id)| self.tcx.def_span(def_id));
2576 Some((ty, span))
2577 }
2578 }
2579 }
2580 ObligationCauseCode::FunctionArg { parent_code, .. } => {
2581 self.get_parent_trait_ref(parent_code)
2582 }
2583 _ => None,
2584 }
2585 }
2586
2587 fn check_same_trait_different_version(
2588 &self,
2589 err: &mut Diag<'_>,
2590 trait_pred: ty::PolyTraitPredicate<'tcx>,
2591 ) -> bool {
2592 let get_trait_impls = |trait_def_id| {
2593 let mut trait_impls = ::alloc::vec::Vec::new()vec![];
2594 self.tcx.for_each_relevant_impl(
2595 trait_def_id,
2596 trait_pred.skip_binder().self_ty(),
2597 |impl_def_id| {
2598 let impl_trait_header = self.tcx.impl_trait_header(impl_def_id);
2599 trait_impls
2600 .push(self.tcx.def_span(impl_trait_header.trait_ref.skip_binder().def_id));
2601 },
2602 );
2603 trait_impls
2604 };
2605 self.check_same_definition_different_crate(
2606 err,
2607 trait_pred.def_id(),
2608 self.tcx.visible_traits(),
2609 get_trait_impls,
2610 "trait",
2611 )
2612 }
2613
2614 pub fn note_two_crate_versions(
2615 &self,
2616 krate: CrateNum,
2617 sp: impl Into<MultiSpan>,
2618 err: &mut Diag<'_>,
2619 ) {
2620 let crate_name = self.tcx.crate_name(krate);
2621 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!(
2622 "there are multiple different versions of crate `{crate_name}` in the dependency graph"
2623 );
2624 err.span_note(sp, crate_msg);
2625 }
2626
2627 fn note_adt_version_mismatch(
2628 &self,
2629 err: &mut Diag<'_>,
2630 trait_pred: ty::PolyTraitPredicate<'tcx>,
2631 ) {
2632 let ty::Adt(impl_self_def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2633 else {
2634 return;
2635 };
2636
2637 let impl_self_did = impl_self_def.did();
2638
2639 if impl_self_did.krate == LOCAL_CRATE {
2642 return;
2643 }
2644
2645 let impl_self_path = self.comparable_path(impl_self_did);
2646 let impl_self_crate_name = self.tcx.crate_name(impl_self_did.krate);
2647 let similar_items: UnordSet<_> = self
2648 .tcx
2649 .visible_parent_map(())
2650 .items()
2651 .filter_map(|(&item, _)| {
2652 if impl_self_did == item {
2654 return None;
2655 }
2656 if item.krate == LOCAL_CRATE {
2659 return None;
2660 }
2661 if impl_self_crate_name != self.tcx.crate_name(item.krate) {
2664 return None;
2665 }
2666 if !self.tcx.def_kind(item).is_adt() {
2669 return None;
2670 }
2671 let path = self.comparable_path(item);
2672 let is_similar = path.ends_with(&impl_self_path) || impl_self_path.ends_with(&path);
2675 is_similar.then_some((item, path))
2676 })
2677 .collect();
2678
2679 let mut similar_items =
2680 similar_items.into_items().into_sorted_stable_ord_by_key(|(_, path)| path);
2681 similar_items.dedup();
2682
2683 for (similar_item, _) in similar_items {
2684 err.span_help(self.tcx.def_span(similar_item), "item with same name found");
2685 self.note_two_crate_versions(similar_item.krate, MultiSpan::new(), err);
2686 }
2687 }
2688
2689 fn check_same_name_different_path(
2690 &self,
2691 err: &mut Diag<'_>,
2692 obligation: &PredicateObligation<'tcx>,
2693 trait_pred: ty::PolyTraitPredicate<'tcx>,
2694 ) -> bool {
2695 let mut suggested = false;
2696 let trait_def_id = trait_pred.def_id();
2697 let trait_has_same_params = |other_trait_def_id: DefId| -> bool {
2698 let trait_generics = self.tcx.generics_of(trait_def_id);
2699 let other_trait_generics = self.tcx.generics_of(other_trait_def_id);
2700
2701 if trait_generics.count() != other_trait_generics.count() {
2702 return false;
2703 }
2704 trait_generics.own_params.iter().zip(other_trait_generics.own_params.iter()).all(
2705 |(a, b)| match (&a.kind, &b.kind) {
2706 (ty::GenericParamDefKind::Lifetime, ty::GenericParamDefKind::Lifetime)
2707 | (
2708 ty::GenericParamDefKind::Type { .. },
2709 ty::GenericParamDefKind::Type { .. },
2710 )
2711 | (
2712 ty::GenericParamDefKind::Const { .. },
2713 ty::GenericParamDefKind::Const { .. },
2714 ) => true,
2715 _ => false,
2716 },
2717 )
2718 };
2719 let trait_name = self.tcx.item_name(trait_def_id);
2720 if let Some(other_trait_def_id) = self.tcx.all_traits_including_private().find(|&def_id| {
2721 trait_def_id != def_id
2722 && trait_name == self.tcx.item_name(def_id)
2723 && trait_has_same_params(def_id)
2724 && !self.tcx.is_lang_item(def_id, LangItem::PointeeSized)
2726 && self.predicate_must_hold_modulo_regions(&Obligation::new(
2727 self.tcx,
2728 obligation.cause.clone(),
2729 obligation.param_env,
2730 trait_pred.map_bound(|tr| ty::TraitPredicate {
2731 trait_ref: ty::TraitRef::new(self.tcx, def_id, tr.trait_ref.args),
2732 ..tr
2733 }),
2734 ))
2735 }) {
2736 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!(
2737 "`{}` implements similarly named trait `{}`, but not `{}`",
2738 trait_pred.self_ty(),
2739 self.tcx.def_path_str(other_trait_def_id),
2740 trait_pred.print_modifiers_and_trait_path()
2741 ));
2742 suggested = true;
2743 }
2744 suggested
2745 }
2746
2747 pub fn note_different_trait_with_same_name(
2752 &self,
2753 err: &mut Diag<'_>,
2754 obligation: &PredicateObligation<'tcx>,
2755 trait_pred: ty::PolyTraitPredicate<'tcx>,
2756 ) -> bool {
2757 if self.check_same_trait_different_version(err, trait_pred) {
2758 return true;
2759 }
2760 self.check_same_name_different_path(err, obligation, trait_pred)
2761 }
2762
2763 fn comparable_path(&self, did: DefId) -> String {
2766 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}",
self.tcx.def_path_str(did)))
})format!("::{}", self.tcx.def_path_str(did))
2767 }
2768
2769 pub(super) fn mk_trait_obligation_with_new_self_ty(
2774 &self,
2775 param_env: ty::ParamEnv<'tcx>,
2776 trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
2777 ) -> PredicateObligation<'tcx> {
2778 let trait_pred = trait_ref_and_ty
2779 .map_bound(|(tr, new_self_ty)| tr.with_replaced_self_ty(self.tcx, new_self_ty));
2780
2781 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
2782 }
2783
2784 fn predicate_can_apply(
2787 &self,
2788 param_env: ty::ParamEnv<'tcx>,
2789 pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + TypeFoldable<TyCtxt<'tcx>>,
2790 ) -> bool {
2791 struct ParamToVarFolder<'a, 'tcx> {
2792 infcx: &'a InferCtxt<'tcx>,
2793 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2794 }
2795
2796 impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
2797 fn cx(&self) -> TyCtxt<'tcx> {
2798 self.infcx.tcx
2799 }
2800
2801 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2802 if let ty::Param(_) = *ty.kind() {
2803 let infcx = self.infcx;
2804 *self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
2805 } else {
2806 ty.super_fold_with(self)
2807 }
2808 }
2809 }
2810
2811 self.probe(|_| {
2812 let cleaned_pred =
2813 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2814
2815 let InferOk { value: cleaned_pred, .. } = self
2816 .infcx
2817 .at(&ObligationCause::dummy(), param_env)
2818 .normalize(Unnormalized::new_wip(cleaned_pred));
2819
2820 let obligation =
2821 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
2822
2823 self.predicate_may_hold(&obligation)
2824 })
2825 }
2826
2827 pub fn note_obligation_cause(
2828 &self,
2829 err: &mut Diag<'_>,
2830 obligation: &PredicateObligation<'tcx>,
2831 ) {
2832 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2835 self.note_obligation_cause_code(
2836 obligation.cause.body_id,
2837 err,
2838 obligation.predicate,
2839 obligation.param_env,
2840 obligation.cause.code(),
2841 &mut ::alloc::vec::Vec::new()vec![],
2842 &mut Default::default(),
2843 );
2844 self.suggest_swapping_lhs_and_rhs(
2845 err,
2846 obligation.predicate,
2847 obligation.param_env,
2848 obligation.cause.code(),
2849 );
2850 self.suggest_borrow_for_unsized_closure_return(
2851 obligation.cause.body_id,
2852 err,
2853 obligation.predicate,
2854 );
2855 self.suggest_unsized_bound_if_applicable(err, obligation);
2856 if let Some(span) = err.span.primary_span()
2857 && let Some(mut diag) =
2858 self.dcx().steal_non_err(span, StashKey::AssociatedTypeSuggestion)
2859 && let Suggestions::Enabled(ref mut s1) = err.suggestions
2860 && let Suggestions::Enabled(ref mut s2) = diag.suggestions
2861 {
2862 s1.append(s2);
2863 diag.cancel()
2864 }
2865 }
2866 }
2867
2868 pub(super) fn is_recursive_obligation(
2869 &self,
2870 obligated_types: &mut Vec<Ty<'tcx>>,
2871 cause_code: &ObligationCauseCode<'tcx>,
2872 ) -> bool {
2873 if let ObligationCauseCode::BuiltinDerived(data) = cause_code {
2874 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2875 let self_ty = parent_trait_ref.skip_binder().self_ty();
2876 if obligated_types.iter().any(|ot| ot == &self_ty) {
2877 return true;
2878 }
2879 if let ty::Adt(def, args) = self_ty.kind()
2880 && let [arg] = &args[..]
2881 && let ty::GenericArgKind::Type(ty) = arg.kind()
2882 && let ty::Adt(inner_def, _) = ty.kind()
2883 && inner_def == def
2884 {
2885 return true;
2886 }
2887 }
2888 false
2889 }
2890
2891 fn get_standard_error_message(
2892 &self,
2893 trait_predicate: ty::PolyTraitPredicate<'tcx>,
2894 predicate_constness: Option<ty::BoundConstness>,
2895 post_message: String,
2896 long_ty_path: &mut Option<PathBuf>,
2897 ) -> String {
2898 ::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!(
2899 "the trait bound `{}` is not satisfied{post_message}",
2900 self.tcx.short_string(
2901 trait_predicate.print_with_bound_constness(predicate_constness),
2902 long_ty_path,
2903 ),
2904 )
2905 }
2906
2907 fn select_transmute_obligation_for_reporting(
2908 &self,
2909 obligation: &PredicateObligation<'tcx>,
2910 trait_predicate: ty::PolyTraitPredicate<'tcx>,
2911 root_obligation: &PredicateObligation<'tcx>,
2912 ) -> (PredicateObligation<'tcx>, ty::PolyTraitPredicate<'tcx>) {
2913 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
2914 return (obligation.clone(), trait_predicate);
2915 }
2916
2917 let ocx = ObligationCtxt::new(self);
2918 let normalized_predicate = self.tcx.erase_and_anonymize_regions(
2919 self.tcx.instantiate_bound_regions_with_erased(trait_predicate),
2920 );
2921 let trait_ref = normalized_predicate.trait_ref;
2922
2923 let assume = ocx.normalize(
2924 &obligation.cause,
2925 obligation.param_env,
2926 Unnormalized::new_wip(trait_ref.args.const_at(2)),
2927 );
2928
2929 let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
2930 return (obligation.clone(), trait_predicate);
2931 };
2932
2933 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!(
2934 rustc_transmute::TransmuteTypeEnv::new(self.tcx).is_transmutable(
2935 trait_ref.args.type_at(1),
2936 trait_ref.args.type_at(0),
2937 assume,
2938 ),
2939 rustc_transmute::Answer::Yes,
2940 );
2941
2942 if is_normalized_yes
2944 && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
2945 root_obligation.predicate.kind().skip_binder()
2946 && root_pred.def_id() == trait_predicate.def_id()
2947 {
2948 return (root_obligation.clone(), root_obligation.predicate.kind().rebind(root_pred));
2949 }
2950
2951 (obligation.clone(), trait_predicate)
2952 }
2953
2954 fn get_safe_transmute_error_and_reason(
2955 &self,
2956 obligation: PredicateObligation<'tcx>,
2957 trait_pred: ty::PolyTraitPredicate<'tcx>,
2958 span: Span,
2959 ) -> GetSafeTransmuteErrorAndReason {
2960 use rustc_transmute::Answer;
2961 self.probe(|_| {
2962 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
2965 return GetSafeTransmuteErrorAndReason::Default;
2966 }
2967
2968 let trait_pred = self.tcx.erase_and_anonymize_regions(
2970 self.tcx.instantiate_bound_regions_with_erased(trait_pred),
2971 );
2972
2973 let ocx = ObligationCtxt::new(self);
2974 let assume = ocx.normalize(
2975 &obligation.cause,
2976 obligation.param_env,
2977 Unnormalized::new_wip(trait_pred.trait_ref.args.const_at(2)),
2978 );
2979
2980 let Some(assume) = rustc_transmute::Assume::from_const(self.infcx.tcx, assume) else {
2981 self.dcx().span_delayed_bug(
2982 span,
2983 "Unable to construct rustc_transmute::Assume where it was previously possible",
2984 );
2985 return GetSafeTransmuteErrorAndReason::Silent;
2986 };
2987
2988 let dst = trait_pred.trait_ref.args.type_at(0);
2989 let src = trait_pred.trait_ref.args.type_at(1);
2990 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}`");
2991
2992 match rustc_transmute::TransmuteTypeEnv::new(self.infcx.tcx)
2993 .is_transmutable(src, dst, assume)
2994 {
2995 Answer::No(reason) => {
2996 let safe_transmute_explanation = match reason {
2997 rustc_transmute::Reason::SrcIsNotYetSupported => {
2998 ::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")
2999 }
3000 rustc_transmute::Reason::DstIsNotYetSupported => {
3001 ::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")
3002 }
3003 rustc_transmute::Reason::DstIsBitIncompatible => {
3004 ::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!(
3005 "at least one value of `{src}` isn't a bit-valid value of `{dst}`"
3006 )
3007 }
3008 rustc_transmute::Reason::DstUninhabited => {
3009 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is uninhabited", dst))
})format!("`{dst}` is uninhabited")
3010 }
3011 rustc_transmute::Reason::DstMayHaveSafetyInvariants => {
3012 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` may carry safety invariants",
dst))
})format!("`{dst}` may carry safety invariants")
3013 }
3014 rustc_transmute::Reason::DstIsTooBig => {
3015 ::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}`")
3016 }
3017 rustc_transmute::Reason::DstRefIsTooBig {
3018 src,
3019 src_size,
3020 dst,
3021 dst_size,
3022 } => {
3023 ::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!(
3024 "the size of `{src}` ({src_size} bytes) \
3025 is smaller than that of `{dst}` ({dst_size} bytes)"
3026 )
3027 }
3028 rustc_transmute::Reason::SrcSizeOverflow => {
3029 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
src))
})format!(
3030 "values of the type `{src}` are too big for the target architecture"
3031 )
3032 }
3033 rustc_transmute::Reason::DstSizeOverflow => {
3034 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
dst))
})format!(
3035 "values of the type `{dst}` are too big for the target architecture"
3036 )
3037 }
3038 rustc_transmute::Reason::DstHasStricterAlignment {
3039 src_min_align,
3040 dst_min_align,
3041 } => {
3042 ::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!(
3043 "the minimum alignment of `{src}` ({src_min_align}) should be \
3044 greater than that of `{dst}` ({dst_min_align})"
3045 )
3046 }
3047 rustc_transmute::Reason::DstIsMoreUnique => {
3048 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is a shared reference, but `{1}` is a unique reference",
src, dst))
})format!(
3049 "`{src}` is a shared reference, but `{dst}` is a unique reference"
3050 )
3051 }
3052 rustc_transmute::Reason::TypeError => {
3054 return GetSafeTransmuteErrorAndReason::Silent;
3055 }
3056 rustc_transmute::Reason::SrcLayoutUnknown => {
3057 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", src))
})format!("`{src}` has an unknown layout")
3058 }
3059 rustc_transmute::Reason::DstLayoutUnknown => {
3060 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", dst))
})format!("`{dst}` has an unknown layout")
3061 }
3062 };
3063 GetSafeTransmuteErrorAndReason::Error {
3064 err_msg,
3065 safe_transmute_explanation: Some(safe_transmute_explanation),
3066 }
3067 }
3068 Answer::Yes => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("Inconsistent rustc_transmute::is_transmutable(...) result, got Yes"))span_bug!(
3070 span,
3071 "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
3072 ),
3073 Answer::If(_) => GetSafeTransmuteErrorAndReason::Error {
3078 err_msg,
3079 safe_transmute_explanation: None,
3080 },
3081 }
3082 })
3083 }
3084
3085 fn find_explicit_cast_type(
3088 &self,
3089 param_env: ty::ParamEnv<'tcx>,
3090 found_ty: Ty<'tcx>,
3091 self_ty: Ty<'tcx>,
3092 ) -> Option<Ty<'tcx>> {
3093 let ty::Ref(region, inner_ty, mutbl) = *found_ty.kind() else {
3094 return None;
3095 };
3096
3097 let mut derefs = (self.autoderef_steps)(inner_ty).into_iter();
3098 derefs.next(); let deref_target = derefs.into_iter().next()?.0;
3100
3101 let cast_ty = Ty::new_ref(self.tcx, region, deref_target, mutbl);
3102
3103 let Some(from_def_id) = self.tcx.get_diagnostic_item(sym::From) else {
3104 return None;
3105 };
3106 let Some(try_from_def_id) = self.tcx.get_diagnostic_item(sym::TryFrom) else {
3107 return None;
3108 };
3109
3110 if self.has_impl_for_type(
3111 param_env,
3112 ty::TraitRef::new(
3113 self.tcx,
3114 from_def_id,
3115 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3116 ),
3117 ) {
3118 Some(cast_ty)
3119 } else if self.has_impl_for_type(
3120 param_env,
3121 ty::TraitRef::new(
3122 self.tcx,
3123 try_from_def_id,
3124 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3125 ),
3126 ) {
3127 Some(cast_ty)
3128 } else {
3129 None
3130 }
3131 }
3132
3133 fn has_impl_for_type(
3134 &self,
3135 param_env: ty::ParamEnv<'tcx>,
3136 trait_ref: ty::TraitRef<'tcx>,
3137 ) -> bool {
3138 let obligation = Obligation::new(
3139 self.tcx,
3140 ObligationCause::dummy(),
3141 param_env,
3142 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive },
3143 );
3144
3145 self.predicate_must_hold_modulo_regions(&obligation)
3146 }
3147
3148 fn add_tuple_trait_message(
3149 &self,
3150 obligation_cause_code: &ObligationCauseCode<'tcx>,
3151 err: &mut Diag<'_>,
3152 ) {
3153 match obligation_cause_code {
3154 ObligationCauseCode::RustCall => {
3155 err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
3156 }
3157 ObligationCauseCode::WhereClause(def_id, _) if self.tcx.is_fn_trait(*def_id) => {
3158 err.code(E0059);
3159 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!(
3160 "type parameter to bare `{}` trait must be a tuple",
3161 self.tcx.def_path_str(*def_id)
3162 ));
3163 }
3164 _ => {}
3165 }
3166 }
3167
3168 fn try_to_add_help_message(
3169 &self,
3170 root_obligation: &PredicateObligation<'tcx>,
3171 obligation: &PredicateObligation<'tcx>,
3172 trait_predicate: ty::PolyTraitPredicate<'tcx>,
3173 err: &mut Diag<'_>,
3174 span: Span,
3175 is_fn_trait: bool,
3176 suggested: bool,
3177 ) {
3178 let body_def_id = obligation.cause.body_id;
3179 let span = if let ObligationCauseCode::BinOp { rhs_span, .. } = obligation.cause.code() {
3180 *rhs_span
3181 } else {
3182 span
3183 };
3184
3185 let trait_def_id = trait_predicate.def_id();
3187 if is_fn_trait
3188 && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
3189 obligation.param_env,
3190 trait_predicate.self_ty(),
3191 trait_predicate.skip_binder().polarity,
3192 )
3193 {
3194 self.add_help_message_for_fn_trait(trait_predicate, err, implemented_kind, params);
3195 } else if !trait_predicate.has_non_region_infer()
3196 && self.predicate_can_apply(obligation.param_env, trait_predicate)
3197 {
3198 self.suggest_restricting_param_bound(
3206 err,
3207 trait_predicate,
3208 None,
3209 obligation.cause.body_id,
3210 );
3211 } else if trait_def_id.is_local()
3212 && self.tcx.trait_impls_of(trait_def_id).is_empty()
3213 && !self.tcx.trait_is_auto(trait_def_id)
3214 && !self.tcx.trait_is_alias(trait_def_id)
3215 && trait_predicate.polarity() == ty::PredicatePolarity::Positive
3216 {
3217 err.span_help(
3218 self.tcx.def_span(trait_def_id),
3219 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"),
3220 );
3221 } else if !suggested && trait_predicate.polarity() == ty::PredicatePolarity::Positive {
3222 let impl_candidates = self.find_similar_impl_candidates(trait_predicate);
3224 if !self.report_similar_impl_candidates(
3225 &impl_candidates,
3226 obligation,
3227 trait_predicate,
3228 body_def_id,
3229 err,
3230 true,
3231 obligation.param_env,
3232 ) {
3233 self.report_similar_impl_candidates_for_root_obligation(
3234 obligation,
3235 trait_predicate,
3236 body_def_id,
3237 err,
3238 );
3239 }
3240
3241 self.suggest_convert_to_slice(
3242 err,
3243 obligation,
3244 trait_predicate,
3245 impl_candidates.as_slice(),
3246 span,
3247 );
3248
3249 self.suggest_tuple_wrapping(err, root_obligation, obligation);
3250 }
3251 self.suggest_shadowed_inherent_method(err, obligation, trait_predicate);
3252 }
3253
3254 fn add_help_message_for_fn_trait(
3255 &self,
3256 trait_pred: ty::PolyTraitPredicate<'tcx>,
3257 err: &mut Diag<'_>,
3258 implemented_kind: ty::ClosureKind,
3259 params: ty::Binder<'tcx, Ty<'tcx>>,
3260 ) {
3261 let selected_kind = self
3268 .tcx
3269 .fn_trait_kind_from_def_id(trait_pred.def_id())
3270 .expect("expected to map DefId to ClosureKind");
3271 if !implemented_kind.extends(selected_kind) {
3272 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!(
3273 "`{}` implements `{}`, but it must implement `{}`, which is more general",
3274 trait_pred.skip_binder().self_ty(),
3275 implemented_kind,
3276 selected_kind
3277 ));
3278 }
3279
3280 let ty::Tuple(given) = *params.skip_binder().kind() else {
3282 return;
3283 };
3284
3285 let expected_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
3286 let ty::Tuple(expected) = *expected_ty.kind() else {
3287 return;
3288 };
3289
3290 if expected.len() != given.len() {
3291 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!(
3293 "expected a closure taking {} argument{}, but one taking {} argument{} was given",
3294 given.len(),
3295 pluralize!(given.len()),
3296 expected.len(),
3297 pluralize!(expected.len()),
3298 ));
3299 return;
3300 }
3301
3302 let given_ty = Ty::new_fn_ptr(
3303 self.tcx,
3304 params.rebind(self.tcx.mk_fn_sig_safe_rust_abi(given, self.tcx.types.unit)),
3305 );
3306 let expected_ty = Ty::new_fn_ptr(
3307 self.tcx,
3308 trait_pred.rebind(self.tcx.mk_fn_sig_safe_rust_abi(expected, self.tcx.types.unit)),
3309 );
3310
3311 if !self.same_type_modulo_infer(given_ty, expected_ty) {
3312 let (expected_args, given_args) = self.cmp(expected_ty, given_ty);
3314 err.note_expected_found(
3315 "a closure with signature",
3316 expected_args,
3317 "a closure with signature",
3318 given_args,
3319 );
3320 }
3321 }
3322
3323 fn report_closure_error(
3324 &self,
3325 obligation: &PredicateObligation<'tcx>,
3326 closure_def_id: DefId,
3327 found_kind: ty::ClosureKind,
3328 kind: ty::ClosureKind,
3329 trait_prefix: &'static str,
3330 ) -> Diag<'a> {
3331 let closure_span = self.tcx.def_span(closure_def_id);
3332
3333 let mut err = ClosureKindMismatch {
3334 closure_span,
3335 expected: kind,
3336 found: found_kind,
3337 cause_span: obligation.cause.span,
3338 trait_prefix,
3339 fn_once_label: None,
3340 fn_mut_label: None,
3341 };
3342
3343 if let Some(typeck_results) = &self.typeck_results {
3346 let hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id.expect_local());
3347 match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
3348 (ty::ClosureKind::FnOnce, Some((span, place))) => {
3349 err.fn_once_label = Some(ClosureFnOnceLabel {
3350 span: *span,
3351 place: ty::place_to_string_for_capture(self.tcx, place),
3352 trait_prefix,
3353 })
3354 }
3355 (ty::ClosureKind::FnMut, Some((span, place))) => {
3356 err.fn_mut_label = Some(ClosureFnMutLabel {
3357 span: *span,
3358 place: ty::place_to_string_for_capture(self.tcx, place),
3359 trait_prefix,
3360 })
3361 }
3362 _ => {}
3363 }
3364 }
3365
3366 self.dcx().create_err(err)
3367 }
3368
3369 fn report_cyclic_signature_error(
3370 &self,
3371 obligation: &PredicateObligation<'tcx>,
3372 found_trait_ref: ty::TraitRef<'tcx>,
3373 expected_trait_ref: ty::TraitRef<'tcx>,
3374 terr: TypeError<'tcx>,
3375 ) -> Diag<'a> {
3376 let self_ty = found_trait_ref.self_ty();
3377 let (cause, terr) = if let ty::Closure(def_id, _) = *self_ty.kind() {
3378 (
3379 ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
3380 TypeError::CyclicTy(self_ty),
3381 )
3382 } else {
3383 (obligation.cause.clone(), terr)
3384 };
3385 self.report_and_explain_type_error(
3386 TypeTrace::trait_refs(&cause, expected_trait_ref, found_trait_ref),
3387 obligation.param_env,
3388 terr,
3389 )
3390 }
3391
3392 fn report_signature_mismatch_error(
3393 &self,
3394 obligation: &PredicateObligation<'tcx>,
3395 span: Span,
3396 found_trait_ref: ty::TraitRef<'tcx>,
3397 expected_trait_ref: ty::TraitRef<'tcx>,
3398 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3399 let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
3400 let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
3401
3402 expected_trait_ref.self_ty().error_reported()?;
3403 let found_trait_ty = found_trait_ref.self_ty();
3404
3405 let found_did = match *found_trait_ty.kind() {
3406 ty::Closure(did, _) | ty::FnDef(did, _) | ty::Coroutine(did, ..) => Some(did),
3407 _ => None,
3408 };
3409
3410 let found_node = found_did.and_then(|did| self.tcx.hir_get_if_local(did));
3411 let found_span = found_did.and_then(|did| self.tcx.hir_span_if_local(did));
3412
3413 if !self.reported_signature_mismatch.borrow_mut().insert((span, found_span)) {
3414 return Err(self.dcx().span_delayed_bug(span, "already_reported"));
3417 }
3418
3419 let mut not_tupled = false;
3420
3421 let found = match found_trait_ref.args.type_at(1).kind() {
3422 ty::Tuple(tys) => ::alloc::vec::from_elem(ArgKind::empty(), tys.len())vec![ArgKind::empty(); tys.len()],
3423 _ => {
3424 not_tupled = true;
3425 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ArgKind::empty()]))vec![ArgKind::empty()]
3426 }
3427 };
3428
3429 let expected_ty = expected_trait_ref.args.type_at(1);
3430 let expected = match expected_ty.kind() {
3431 ty::Tuple(tys) => {
3432 tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
3433 }
3434 _ => {
3435 not_tupled = true;
3436 ::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())]
3437 }
3438 };
3439
3440 if !self.tcx.is_lang_item(expected_trait_ref.def_id, LangItem::Coroutine) && not_tupled {
3446 return Ok(self.report_and_explain_type_error(
3447 TypeTrace::trait_refs(&obligation.cause, expected_trait_ref, found_trait_ref),
3448 obligation.param_env,
3449 ty::error::TypeError::Mismatch,
3450 ));
3451 }
3452 if found.len() != expected.len() {
3453 let (closure_span, closure_arg_span, found) = found_did
3454 .and_then(|did| {
3455 let node = self.tcx.hir_get_if_local(did)?;
3456 let (found_span, closure_arg_span, found) = self.get_fn_like_arguments(node)?;
3457 Some((Some(found_span), closure_arg_span, found))
3458 })
3459 .unwrap_or((found_span, None, found));
3460
3461 if found.len() != expected.len() {
3467 return Ok(self.report_arg_count_mismatch(
3468 span,
3469 closure_span,
3470 expected,
3471 found,
3472 found_trait_ty.is_closure(),
3473 closure_arg_span,
3474 ));
3475 }
3476 }
3477 Ok(self.report_closure_arg_mismatch(
3478 span,
3479 found_span,
3480 found_trait_ref,
3481 expected_trait_ref,
3482 obligation.cause.code(),
3483 found_node,
3484 obligation.param_env,
3485 ))
3486 }
3487
3488 pub fn get_fn_like_arguments(
3493 &self,
3494 node: Node<'_>,
3495 ) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
3496 let sm = self.tcx.sess.source_map();
3497 Some(match node {
3498 Node::Expr(&hir::Expr {
3499 kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
3500 ..
3501 }) => (
3502 fn_decl_span,
3503 fn_arg_span,
3504 self.tcx
3505 .hir_body(body)
3506 .params
3507 .iter()
3508 .map(|arg| {
3509 if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat
3510 {
3511 Some(ArgKind::Tuple(
3512 Some(span),
3513 args.iter()
3514 .map(|pat| {
3515 sm.span_to_snippet(pat.span)
3516 .ok()
3517 .map(|snippet| (snippet, "_".to_owned()))
3518 })
3519 .collect::<Option<Vec<_>>>()?,
3520 ))
3521 } else {
3522 let name = sm.span_to_snippet(arg.pat.span).ok()?;
3523 Some(ArgKind::Arg(name, "_".to_owned()))
3524 }
3525 })
3526 .collect::<Option<Vec<ArgKind>>>()?,
3527 ),
3528 Node::Item(&hir::Item { kind: hir::ItemKind::Fn { ref sig, .. }, .. })
3529 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
3530 | Node::TraitItem(&hir::TraitItem {
3531 kind: hir::TraitItemKind::Fn(ref sig, _), ..
3532 })
3533 | Node::ForeignItem(&hir::ForeignItem {
3534 kind: hir::ForeignItemKind::Fn(ref sig, _, _),
3535 ..
3536 }) => (
3537 sig.span,
3538 None,
3539 sig.decl
3540 .inputs
3541 .iter()
3542 .map(|arg| match arg.kind {
3543 hir::TyKind::Tup(tys) => ArgKind::Tuple(
3544 Some(arg.span),
3545 ::alloc::vec::from_elem(("_".to_owned(), "_".to_owned()), tys.len())vec![("_".to_owned(), "_".to_owned()); tys.len()],
3546 ),
3547 _ => ArgKind::empty(),
3548 })
3549 .collect::<Vec<ArgKind>>(),
3550 ),
3551 Node::Ctor(variant_data) => {
3552 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| self.tcx.hir_span(id));
3553 (span, None, ::alloc::vec::from_elem(ArgKind::empty(), variant_data.fields().len())vec![ArgKind::empty(); variant_data.fields().len()])
3554 }
3555 _ => {
::core::panicking::panic_fmt(format_args!("non-FnLike node found: {0:?}",
node));
}panic!("non-FnLike node found: {node:?}"),
3556 })
3557 }
3558
3559 pub fn report_arg_count_mismatch(
3563 &self,
3564 span: Span,
3565 found_span: Option<Span>,
3566 expected_args: Vec<ArgKind>,
3567 found_args: Vec<ArgKind>,
3568 is_closure: bool,
3569 closure_arg_span: Option<Span>,
3570 ) -> Diag<'a> {
3571 let kind = if is_closure { "closure" } else { "function" };
3572
3573 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
3574 let arg_length = arguments.len();
3575 let distinct = #[allow(non_exhaustive_omitted_patterns)] match other {
&[ArgKind::Tuple(..)] => true,
_ => false,
}matches!(other, &[ArgKind::Tuple(..)]);
3576 match (arg_length, arguments.get(0)) {
3577 (1, Some(ArgKind::Tuple(_, fields))) => {
3578 ::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())
3579 }
3580 _ => ::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!(
3581 "{} {}argument{}",
3582 arg_length,
3583 if distinct && arg_length > 1 { "distinct " } else { "" },
3584 pluralize!(arg_length)
3585 ),
3586 }
3587 };
3588
3589 let expected_str = args_str(&expected_args, &found_args);
3590 let found_str = args_str(&found_args, &expected_args);
3591
3592 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!(
3593 self.dcx(),
3594 span,
3595 E0593,
3596 "{} is expected to take {}, but it takes {}",
3597 kind,
3598 expected_str,
3599 found_str,
3600 );
3601
3602 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}"));
3603
3604 if let Some(found_span) = found_span {
3605 err.span_label(found_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("takes {0}", found_str))
})format!("takes {found_str}"));
3606
3607 if found_args.is_empty() && is_closure {
3611 let underscores = ::alloc::vec::from_elem("_", expected_args.len())vec!["_"; expected_args.len()].join(", ");
3612 err.span_suggestion_verbose(
3613 closure_arg_span.unwrap_or(found_span),
3614 ::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!(
3615 "consider changing the closure to take and ignore the expected argument{}",
3616 pluralize!(expected_args.len())
3617 ),
3618 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", underscores))
})format!("|{underscores}|"),
3619 Applicability::MachineApplicable,
3620 );
3621 }
3622
3623 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
3624 if fields.len() == expected_args.len() {
3625 let sugg = fields
3626 .iter()
3627 .map(|(name, _)| name.to_owned())
3628 .collect::<Vec<String>>()
3629 .join(", ");
3630 err.span_suggestion_verbose(
3631 found_span,
3632 "change the closure to take multiple arguments instead of a single tuple",
3633 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", sugg))
})format!("|{sugg}|"),
3634 Applicability::MachineApplicable,
3635 );
3636 }
3637 }
3638 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
3639 && fields.len() == found_args.len()
3640 && is_closure
3641 {
3642 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!(
3643 "|({}){}|",
3644 found_args
3645 .iter()
3646 .map(|arg| match arg {
3647 ArgKind::Arg(name, _) => name.to_owned(),
3648 _ => "_".to_owned(),
3649 })
3650 .collect::<Vec<String>>()
3651 .join(", "),
3652 if found_args.iter().any(|arg| match arg {
3654 ArgKind::Arg(_, ty) => ty != "_",
3655 _ => false,
3656 }) {
3657 format!(
3658 ": ({})",
3659 fields
3660 .iter()
3661 .map(|(_, ty)| ty.to_owned())
3662 .collect::<Vec<String>>()
3663 .join(", ")
3664 )
3665 } else {
3666 String::new()
3667 },
3668 );
3669 err.span_suggestion_verbose(
3670 found_span,
3671 "change the closure to accept a tuple instead of individual arguments",
3672 sugg,
3673 Applicability::MachineApplicable,
3674 );
3675 }
3676 }
3677
3678 err
3679 }
3680
3681 pub fn type_implements_fn_trait(
3685 &self,
3686 param_env: ty::ParamEnv<'tcx>,
3687 ty: ty::Binder<'tcx, Ty<'tcx>>,
3688 polarity: ty::PredicatePolarity,
3689 ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
3690 self.commit_if_ok(|_| {
3691 for trait_def_id in [
3692 self.tcx.lang_items().fn_trait(),
3693 self.tcx.lang_items().fn_mut_trait(),
3694 self.tcx.lang_items().fn_once_trait(),
3695 ] {
3696 let Some(trait_def_id) = trait_def_id else { continue };
3697 let var = self.next_ty_var(DUMMY_SP);
3700 let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
3702 let obligation = Obligation::new(
3703 self.tcx,
3704 ObligationCause::dummy(),
3705 param_env,
3706 ty.rebind(ty::TraitPredicate { trait_ref, polarity }),
3707 );
3708 let ocx = ObligationCtxt::new(self);
3709 ocx.register_obligation(obligation);
3710 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
3711 return Ok((
3712 self.tcx
3713 .fn_trait_kind_from_def_id(trait_def_id)
3714 .expect("expected to map DefId to ClosureKind"),
3715 ty.rebind(self.resolve_vars_if_possible(var)),
3716 ));
3717 }
3718 }
3719
3720 Err(())
3721 })
3722 }
3723
3724 fn report_not_const_evaluatable_error(
3725 &self,
3726 obligation: &PredicateObligation<'tcx>,
3727 span: Span,
3728 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3729 if !self.tcx.features().generic_const_exprs()
3730 && !self.tcx.features().min_generic_const_args()
3731 {
3732 let guar = self
3733 .dcx()
3734 .struct_span_err(span, "constant expression depends on a generic parameter")
3735 .with_note("this may fail depending on what value the parameter takes")
3742 .emit();
3743 return Err(guar);
3744 }
3745
3746 match obligation.predicate.kind().skip_binder() {
3747 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => match ct.kind() {
3748 ty::ConstKind::Unevaluated(uv) => {
3749 let mut err =
3750 self.dcx().struct_span_err(span, "unconstrained generic constant");
3751 let const_span = uv.kind.def_span(self.tcx);
3752
3753 let const_ty = uv.type_of(self.tcx).skip_norm_wip();
3754 let cast = if const_ty != self.tcx.types.usize { " as usize" } else { "" };
3755 let msg = "try adding a `where` bound";
3756 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(const_span) {
3757 let code = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); {0}{1}]:", snippet, cast))
})format!("[(); {snippet}{cast}]:");
3758 let suggestion_def_id = if let ObligationCauseCode::CompareImplItem {
3759 trait_item_def_id,
3760 ..
3761 } = obligation.cause.code()
3762 {
3763 trait_item_def_id.as_local()
3764 } else {
3765 Some(obligation.cause.body_id)
3766 };
3767 if let Some(suggestion_def_id) = suggestion_def_id
3768 && let Some(generics) = self.tcx.hir_get_generics(suggestion_def_id)
3769 {
3770 err.span_suggestion_verbose(
3771 generics.tail_span_for_predicate_suggestion(),
3772 msg,
3773 ::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()),
3774 Applicability::MaybeIncorrect,
3775 );
3776 } else {
3777 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: where {1}", msg, code))
})format!("{msg}: where {code}"));
3778 };
3779 } else {
3780 err.help(msg);
3781 }
3782 Ok(err)
3783 }
3784 ty::ConstKind::Expr(_) => {
3785 let err = self
3786 .dcx()
3787 .struct_span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unconstrained generic constant `{0}`",
ct))
})format!("unconstrained generic constant `{ct}`"));
3788 Ok(err)
3789 }
3790 _ => {
3791 ::rustc_middle::util::bug::bug_fmt(format_args!("const evaluatable failed for non-unevaluated const `{0:?}`",
ct));bug!("const evaluatable failed for non-unevaluated const `{ct:?}`");
3792 }
3793 },
3794 _ => {
3795 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpected non-ConstEvaluatable predicate, this should not be reachable"))span_bug!(
3796 span,
3797 "unexpected non-ConstEvaluatable predicate, this should not be reachable"
3798 )
3799 }
3800 }
3801 }
3802}