1use core::ops::ControlFlow;
2use std::borrow::Cow;
3use std::path::PathBuf;
4
5use rustc_ast::TraitObjectSyntax;
6use rustc_data_structures::fx::FxHashMap;
7use rustc_data_structures::unord::UnordSet;
8use rustc_errors::codes::*;
9use rustc_errors::{
10 Applicability, Diag, ErrorGuaranteed, Level, MultiSpan, StashKey, StringPart, Suggestions,
11 pluralize, struct_span_code_err,
12};
13use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
14use rustc_hir::intravisit::Visitor;
15use rustc_hir::{self as hir, LangItem, Node};
16use rustc_infer::infer::{InferOk, TypeTrace};
17use rustc_middle::traits::SignatureMismatchData;
18use rustc_middle::traits::select::OverflowError;
19use rustc_middle::ty::abstract_const::NotConstEvaluatable;
20use rustc_middle::ty::error::{ExpectedFound, TypeError};
21use rustc_middle::ty::fold::{TypeFolder, TypeSuperFoldable};
22use rustc_middle::ty::print::{
23 PrintPolyTraitPredicateExt, PrintTraitPredicateExt as _, PrintTraitRefExt as _,
24 with_forced_trimmed_paths,
25};
26use rustc_middle::ty::{self, TraitRef, Ty, TyCtxt, TypeFoldable, TypeVisitableExt, Upcast};
27use rustc_middle::{bug, span_bug};
28use rustc_span::{BytePos, DUMMY_SP, STDLIB_STABLE_CRATES, Span, Symbol, sym};
29use tracing::{debug, instrument};
30
31use super::on_unimplemented::{AppendConstMessage, OnUnimplementedNote};
32use super::suggestions::get_explanation_based_on_obligation;
33use super::{
34 ArgKind, CandidateSimilarity, FindExprBySpan, GetSafeTransmuteErrorAndReason, ImplCandidate,
35 UnsatisfiedConst,
36};
37use crate::error_reporting::TypeErrCtxt;
38use crate::error_reporting::infer::TyCategory;
39use crate::error_reporting::traits::report_dyn_incompatibility;
40use crate::errors::{
41 AsyncClosureNotFn, ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch,
42};
43use crate::infer::{self, InferCtxt, InferCtxtExt as _};
44use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
45use crate::traits::{
46 MismatchedProjectionTypes, NormalizeExt, Obligation, ObligationCause, ObligationCauseCode,
47 ObligationCtxt, Overflow, PredicateObligation, SelectionError, SignatureMismatch,
48 TraitDynIncompatible, elaborate,
49};
50
51impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
52 pub fn report_selection_error(
56 &self,
57 mut obligation: PredicateObligation<'tcx>,
58 root_obligation: &PredicateObligation<'tcx>,
59 error: &SelectionError<'tcx>,
60 ) -> ErrorGuaranteed {
61 let tcx = self.tcx;
62 let mut span = obligation.cause.span;
63 let mut long_ty_file = None;
64
65 let mut err = match *error {
66 SelectionError::Unimplemented => {
67 if let ObligationCauseCode::WellFormed(Some(wf_loc)) =
70 root_obligation.cause.code().peel_derives()
71 && !obligation.predicate.has_non_region_infer()
72 {
73 if let Some(cause) = self
74 .tcx
75 .diagnostic_hir_wf_check((tcx.erase_regions(obligation.predicate), *wf_loc))
76 {
77 obligation.cause = cause.clone();
78 span = obligation.cause.span;
79 }
80 }
81
82 if let ObligationCauseCode::CompareImplItem {
83 impl_item_def_id,
84 trait_item_def_id,
85 kind: _,
86 } = *obligation.cause.code()
87 {
88 debug!("ObligationCauseCode::CompareImplItemObligation");
89 return self.report_extra_impl_obligation(
90 span,
91 impl_item_def_id,
92 trait_item_def_id,
93 &format!("`{}`", obligation.predicate),
94 )
95 .emit()
96 }
97
98 if let ObligationCauseCode::ConstParam(ty) = *obligation.cause.code().peel_derives()
100 {
101 return self.report_const_param_not_wf(ty, &obligation).emit();
102 }
103
104 let bound_predicate = obligation.predicate.kind();
105 match bound_predicate.skip_binder() {
106 ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_predicate)) => {
107 let leaf_trait_predicate =
108 self.resolve_vars_if_possible(bound_predicate.rebind(trait_predicate));
109
110 let (main_trait_predicate, main_obligation) = if let ty::PredicateKind::Clause(
117 ty::ClauseKind::Trait(root_pred)
118 ) = root_obligation.predicate.kind().skip_binder()
119 && !leaf_trait_predicate.self_ty().skip_binder().has_escaping_bound_vars()
120 && !root_pred.self_ty().has_escaping_bound_vars()
121 && (
126 self.can_eq(
128 obligation.param_env,
129 leaf_trait_predicate.self_ty().skip_binder(),
130 root_pred.self_ty().peel_refs(),
131 )
132 || self.can_eq(
134 obligation.param_env,
135 leaf_trait_predicate.self_ty().skip_binder(),
136 root_pred.self_ty(),
137 )
138 )
139 && leaf_trait_predicate.def_id() != root_pred.def_id()
143 && Some(root_pred.def_id()) != self.tcx.lang_items().unsize_trait()
146 {
147 (
148 self.resolve_vars_if_possible(
149 root_obligation.predicate.kind().rebind(root_pred),
150 ),
151 root_obligation,
152 )
153 } else {
154 (leaf_trait_predicate, &obligation)
155 };
156
157 if let Some(guar) = self.emit_specialized_closure_kind_error(
158 &obligation,
159 leaf_trait_predicate,
160 ) {
161 return guar;
162 }
163
164 if let Err(guar) = leaf_trait_predicate.error_reported()
165 {
166 return guar;
167 }
168 if let Err(guar) = self.fn_arg_obligation(&obligation) {
171 return guar;
172 }
173 let (post_message, pre_message, type_def) = self
174 .get_parent_trait_ref(obligation.cause.code())
175 .map(|(t, s)| {
176 let t = self.tcx.short_string(t, &mut long_ty_file);
177 (
178 format!(" in `{t}`"),
179 format!("within `{t}`, "),
180 s.map(|s| (format!("within this `{t}`"), s)),
181 )
182 })
183 .unwrap_or_default();
184
185 let OnUnimplementedNote {
186 message,
187 label,
188 notes,
189 parent_label,
190 append_const_msg,
191 } = self.on_unimplemented_note(main_trait_predicate, main_obligation, &mut long_ty_file);
192
193 let have_alt_message = message.is_some() || label.is_some();
194 let is_try_conversion = self.is_try_conversion(span, main_trait_predicate.def_id());
195 let is_unsize =
196 self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Unsize);
197 let (message, notes, append_const_msg) = if is_try_conversion {
198 (
199 Some(format!(
200 "`?` couldn't convert the error to `{}`",
201 main_trait_predicate.skip_binder().self_ty(),
202 )),
203 vec![
204 "the question mark operation (`?`) implicitly performs a \
205 conversion on the error value using the `From` trait"
206 .to_owned(),
207 ],
208 Some(AppendConstMessage::Default),
209 )
210 } else {
211 (message, notes, append_const_msg)
212 };
213
214 let err_msg = self.get_standard_error_message(
215 main_trait_predicate,
216 message,
217 None,
218 append_const_msg,
219 post_message,
220 &mut long_ty_file,
221 );
222
223 let (err_msg, safe_transmute_explanation) = if self.tcx.is_lang_item(main_trait_predicate.def_id(), LangItem::TransmuteTrait)
224 {
225 match self.get_safe_transmute_error_and_reason(
227 obligation.clone(),
228 main_trait_predicate,
229 span,
230 ) {
231 GetSafeTransmuteErrorAndReason::Silent => {
232 return self.dcx().span_delayed_bug(
233 span, "silent safe transmute error"
234 );
235 }
236 GetSafeTransmuteErrorAndReason::Default => {
237 (err_msg, None)
238 }
239 GetSafeTransmuteErrorAndReason::Error {
240 err_msg,
241 safe_transmute_explanation,
242 } => (err_msg, safe_transmute_explanation),
243 }
244 } else {
245 (err_msg, None)
246 };
247
248 let mut err = struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg);
249 *err.long_ty_path() = long_ty_file;
250
251 let mut suggested = false;
252 if is_try_conversion {
253 suggested = self.try_conversion_context(&obligation, main_trait_predicate, &mut err);
254 }
255
256 if is_try_conversion && let Some(ret_span) = self.return_type_span(&obligation) {
257 err.span_label(
258 ret_span,
259 format!(
260 "expected `{}` because of this",
261 main_trait_predicate.skip_binder().self_ty()
262 ),
263 );
264 }
265
266 if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Tuple) {
267 self.add_tuple_trait_message(
268 obligation.cause.code().peel_derives(),
269 &mut err,
270 );
271 }
272
273 let explanation = get_explanation_based_on_obligation(
274 self.tcx,
275 &obligation,
276 leaf_trait_predicate,
277 pre_message,
278 );
279
280 self.check_for_binding_assigned_block_without_tail_expression(
281 &obligation,
282 &mut err,
283 leaf_trait_predicate,
284 );
285 self.suggest_add_result_as_return_type(
286 &obligation,
287 &mut err,
288 leaf_trait_predicate,
289 );
290
291 if self.suggest_add_reference_to_arg(
292 &obligation,
293 &mut err,
294 leaf_trait_predicate,
295 have_alt_message,
296 ) {
297 self.note_obligation_cause(&mut err, &obligation);
298 return err.emit();
299 }
300
301 if let Some(s) = label {
302 err.span_label(span, s);
305 if !matches!(leaf_trait_predicate.skip_binder().self_ty().kind(), ty::Param(_)) {
306 err.help(explanation);
310 }
311 } else if let Some(custom_explanation) = safe_transmute_explanation {
312 err.span_label(span, custom_explanation);
313 } else if explanation.len() > self.tcx.sess.diagnostic_width() {
314 err.span_label(span, "unsatisfied trait bound");
317 err.help(explanation);
318 } else {
319 err.span_label(span, explanation);
320 }
321
322 if let ObligationCauseCode::Coercion { source, target } =
323 *obligation.cause.code().peel_derives()
324 {
325 if self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Sized) {
326 self.suggest_borrowing_for_object_cast(
327 &mut err,
328 root_obligation,
329 source,
330 target,
331 );
332 }
333 }
334
335 let UnsatisfiedConst(unsatisfied_const) = self
336 .maybe_add_note_for_unsatisfied_const(
337 leaf_trait_predicate,
338 &mut err,
339 span,
340 );
341
342 if let Some((msg, span)) = type_def {
343 err.span_label(span, msg);
344 }
345 for note in notes {
346 err.note(note);
348 }
349 if let Some(s) = parent_label {
350 let body = obligation.cause.body_id;
351 err.span_label(tcx.def_span(body), s);
352 }
353
354 self.suggest_floating_point_literal(&obligation, &mut err, leaf_trait_predicate);
355 self.suggest_dereferencing_index(&obligation, &mut err, leaf_trait_predicate);
356 suggested |= self.suggest_dereferences(&obligation, &mut err, leaf_trait_predicate);
357 suggested |= self.suggest_fn_call(&obligation, &mut err, leaf_trait_predicate);
358 let impl_candidates = self.find_similar_impl_candidates(leaf_trait_predicate);
359 suggested = if let &[cand] = &impl_candidates[..] {
360 let cand = cand.trait_ref;
361 if let (ty::FnPtr(..), ty::FnDef(..)) =
362 (cand.self_ty().kind(), main_trait_predicate.self_ty().skip_binder().kind())
363 {
364 let suggestion = if self.tcx.sess.source_map().span_look_ahead(span, ".", Some(50)).is_some() {
366 vec![
367 (span.shrink_to_lo(), format!("(")),
368 (span.shrink_to_hi(), format!(" as {})", cand.self_ty())),
369 ]
370 } else if let Some(body) = self.tcx.hir().maybe_body_owned_by(obligation.cause.body_id) {
371 let mut expr_finder = FindExprBySpan::new(span, self.tcx);
372 expr_finder.visit_expr(body.value);
373 if let Some(expr) = expr_finder.result &&
374 let hir::ExprKind::AddrOf(_, _, expr) = expr.kind {
375 vec![
376 (expr.span.shrink_to_lo(), format!("(")),
377 (expr.span.shrink_to_hi(), format!(" as {})", cand.self_ty())),
378 ]
379 } else {
380 vec![(span.shrink_to_hi(), format!(" as {}", cand.self_ty()))]
381 }
382 } else {
383 vec![(span.shrink_to_hi(), format!(" as {}", cand.self_ty()))]
384 };
385 err.multipart_suggestion(
386 format!(
387 "the trait `{}` is implemented for fn pointer `{}`, try casting using `as`",
388 cand.print_trait_sugared(),
389 cand.self_ty(),
390 ),
391 suggestion,
392 Applicability::MaybeIncorrect,
393 );
394 true
395 } else {
396 false
397 }
398 } else {
399 false
400 } || suggested;
401 suggested |=
402 self.suggest_remove_reference(&obligation, &mut err, leaf_trait_predicate);
403 suggested |= self.suggest_semicolon_removal(
404 &obligation,
405 &mut err,
406 span,
407 leaf_trait_predicate,
408 );
409 self.note_version_mismatch(&mut err, leaf_trait_predicate);
410 self.suggest_remove_await(&obligation, &mut err);
411 self.suggest_derive(&obligation, &mut err, leaf_trait_predicate);
412
413 if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Try) {
414 self.suggest_await_before_try(
415 &mut err,
416 &obligation,
417 leaf_trait_predicate,
418 span,
419 );
420 }
421
422 if self.suggest_add_clone_to_arg(&obligation, &mut err, leaf_trait_predicate) {
423 return err.emit();
424 }
425
426 if self.suggest_impl_trait(&mut err, &obligation, leaf_trait_predicate) {
427 return err.emit();
428 }
429
430 if is_unsize {
431 err.note(
434 "all implementations of `Unsize` are provided \
435 automatically by the compiler, see \
436 <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
437 for more information",
438 );
439 }
440
441 let is_fn_trait = tcx.is_fn_trait(leaf_trait_predicate.def_id());
442 let is_target_feature_fn = if let ty::FnDef(def_id, _) =
443 *leaf_trait_predicate.skip_binder().self_ty().kind()
444 {
445 !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
446 } else {
447 false
448 };
449 if is_fn_trait && is_target_feature_fn {
450 err.note(
451 "`#[target_feature]` functions do not implement the `Fn` traits",
452 );
453 err.note(
454 "try casting the function to a `fn` pointer or wrapping it in a closure",
455 );
456 }
457
458 self.try_to_add_help_message(
459 &root_obligation,
460 &obligation,
461 leaf_trait_predicate,
462 &mut err,
463 span,
464 is_fn_trait,
465 suggested,
466 unsatisfied_const,
467 );
468
469 if !is_unsize {
472 self.suggest_change_mut(&obligation, &mut err, leaf_trait_predicate);
473 }
474
475 if leaf_trait_predicate.skip_binder().self_ty().is_never()
480 && self.fallback_has_occurred
481 {
482 let predicate = leaf_trait_predicate.map_bound(|trait_pred| {
483 trait_pred.with_self_ty(self.tcx, tcx.types.unit)
484 });
485 let unit_obligation = obligation.with(tcx, predicate);
486 if self.predicate_may_hold(&unit_obligation) {
487 err.note(
488 "this error might have been caused by changes to \
489 Rust's type-inference algorithm (see issue #48950 \
490 <https://github.com/rust-lang/rust/issues/48950> \
491 for more information)",
492 );
493 err.help("did you intend to use the type `()` here instead?");
494 }
495 }
496
497 self.explain_hrtb_projection(&mut err, leaf_trait_predicate, obligation.param_env, &obligation.cause);
498 self.suggest_desugaring_async_fn_in_trait(&mut err, main_trait_predicate);
499
500 let in_std_macro =
506 match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
507 Some(macro_def_id) => {
508 let crate_name = tcx.crate_name(macro_def_id.krate);
509 STDLIB_STABLE_CRATES.contains(&crate_name)
510 }
511 None => false,
512 };
513
514 if in_std_macro
515 && matches!(
516 self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id()),
517 Some(sym::Debug | sym::Display)
518 )
519 {
520 return err.emit();
521 }
522
523 err
524 }
525
526 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(predicate)) => {
527 self.report_host_effect_error(bound_predicate.rebind(predicate), obligation.param_env, span)
528 }
529
530 ty::PredicateKind::Subtype(predicate) => {
531 span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
535 }
536
537 ty::PredicateKind::Coerce(predicate) => {
538 span_bug!(span, "coerce requirement gave wrong error: `{:?}`", predicate)
542 }
543
544 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..))
545 | ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..)) => {
546 span_bug!(
547 span,
548 "outlives clauses should not error outside borrowck. obligation: `{:?}`",
549 obligation
550 )
551 }
552
553 ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => {
554 span_bug!(
555 span,
556 "projection clauses should be implied from elsewhere. obligation: `{:?}`",
557 obligation
558 )
559 }
560
561 ty::PredicateKind::DynCompatible(trait_def_id) => {
562 let violations = self.tcx.dyn_compatibility_violations(trait_def_id);
563 let mut err = report_dyn_incompatibility(
564 self.tcx,
565 span,
566 None,
567 trait_def_id,
568 violations,
569 );
570 if let hir::Node::Item(item) =
571 self.tcx.hir_node_by_def_id(obligation.cause.body_id)
572 && let hir::ItemKind::Impl(impl_) = item.kind
573 && let None = impl_.of_trait
574 && let hir::TyKind::TraitObject(_, tagged_ptr) = impl_.self_ty.kind
575 && let TraitObjectSyntax::None = tagged_ptr.tag()
576 && impl_.self_ty.span.edition().at_least_rust_2021()
577 {
578 err.downgrade_to_delayed_bug();
581 }
582 err
583 }
584
585 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(ty)) => {
586 let ty = self.resolve_vars_if_possible(ty);
587 if self.next_trait_solver() {
588 if let Err(guar) = ty.error_reported() {
589 return guar;
590 }
591
592 self.dcx().struct_span_err(
595 span,
596 format!("the type `{ty}` is not well-formed"),
597 )
598 } else {
599 span_bug!(span, "WF predicate not satisfied for {:?}", ty);
605 }
606 }
607
608 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
612 | ty::PredicateKind::ConstEquate { .. }
616 | ty::PredicateKind::Ambiguous
618 | ty::PredicateKind::NormalizesTo { .. }
619 | ty::PredicateKind::AliasRelate { .. }
620 | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType { .. }) => {
621 span_bug!(
622 span,
623 "Unexpected `Predicate` for `SelectionError`: `{:?}`",
624 obligation
625 )
626 }
627 }
628 }
629
630 SignatureMismatch(box SignatureMismatchData {
631 found_trait_ref,
632 expected_trait_ref,
633 terr: terr @ TypeError::CyclicTy(_),
634 }) => self.report_cyclic_signature_error(
635 &obligation,
636 found_trait_ref,
637 expected_trait_ref,
638 terr,
639 ),
640 SignatureMismatch(box SignatureMismatchData {
641 found_trait_ref,
642 expected_trait_ref,
643 terr: _,
644 }) => {
645 match self.report_signature_mismatch_error(
646 &obligation,
647 span,
648 found_trait_ref,
649 expected_trait_ref,
650 ) {
651 Ok(err) => err,
652 Err(guar) => return guar,
653 }
654 }
655
656 SelectionError::OpaqueTypeAutoTraitLeakageUnknown(def_id) => return self.report_opaque_type_auto_trait_leakage(
657 &obligation,
658 def_id,
659 ),
660
661 TraitDynIncompatible(did) => {
662 let violations = self.tcx.dyn_compatibility_violations(did);
663 report_dyn_incompatibility(self.tcx, span, None, did, violations)
664 }
665
666 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
667 bug!(
668 "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
669 )
670 }
671 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
672 match self.report_not_const_evaluatable_error(&obligation, span) {
673 Ok(err) => err,
674 Err(guar) => return guar,
675 }
676 }
677
678 SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(guar)) |
680 Overflow(OverflowError::Error(guar)) => {
682 self.set_tainted_by_errors(guar);
683 return guar
684 },
685
686 Overflow(_) => {
687 bug!("overflow should be handled before the `report_selection_error` path");
688 }
689
690 SelectionError::ConstArgHasWrongType { ct, ct_ty, expected_ty } => {
691 let mut diag = self.dcx().struct_span_err(
692 span,
693 format!("the constant `{ct}` is not of type `{expected_ty}`"),
694 );
695
696 self.note_type_err(
697 &mut diag,
698 &obligation.cause,
699 None,
700 None,
701 TypeError::Sorts(ty::error::ExpectedFound::new(expected_ty, ct_ty)),
702 false,
703 None,
704 );
705 diag
706 }
707 };
708
709 self.note_obligation_cause(&mut err, &obligation);
710 self.point_at_returns_when_relevant(&mut err, &obligation);
711 err.emit()
712 }
713}
714
715impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
716 pub(super) fn apply_do_not_recommend(
717 &self,
718 obligation: &mut PredicateObligation<'tcx>,
719 ) -> bool {
720 let mut base_cause = obligation.cause.code().clone();
721 let mut applied_do_not_recommend = false;
722 loop {
723 if let ObligationCauseCode::ImplDerived(ref c) = base_cause {
724 if self.tcx.do_not_recommend_impl(c.impl_or_alias_def_id) {
725 let code = (*c.derived.parent_code).clone();
726 obligation.cause.map_code(|_| code);
727 obligation.predicate = c.derived.parent_trait_pred.upcast(self.tcx);
728 applied_do_not_recommend = true;
729 }
730 }
731 if let Some(parent_cause) = base_cause.parent() {
732 base_cause = parent_cause.clone();
733 } else {
734 break;
735 }
736 }
737
738 applied_do_not_recommend
739 }
740
741 fn report_host_effect_error(
742 &self,
743 predicate: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
744 param_env: ty::ParamEnv<'tcx>,
745 span: Span,
746 ) -> Diag<'a> {
747 let trait_ref = predicate.map_bound(|predicate| ty::TraitPredicate {
754 trait_ref: predicate.trait_ref,
755 polarity: ty::PredicatePolarity::Positive,
756 });
757 let mut file = None;
758 let err_msg = self.get_standard_error_message(
759 trait_ref,
760 None,
761 Some(predicate.constness()),
762 None,
763 String::new(),
764 &mut file,
765 );
766 let mut diag = struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg);
767 *diag.long_ty_path() = file;
768 if !self.predicate_may_hold(&Obligation::new(
769 self.tcx,
770 ObligationCause::dummy(),
771 param_env,
772 trait_ref,
773 )) {
774 diag.downgrade_to_delayed_bug();
775 }
776 diag
777 }
778
779 fn emit_specialized_closure_kind_error(
780 &self,
781 obligation: &PredicateObligation<'tcx>,
782 mut trait_pred: ty::PolyTraitPredicate<'tcx>,
783 ) -> Option<ErrorGuaranteed> {
784 if self.tcx.is_lang_item(trait_pred.def_id(), LangItem::AsyncFnKindHelper)
789 && let Some(found_kind) =
790 trait_pred.skip_binder().trait_ref.args.type_at(0).to_opt_closure_kind()
791 && let Some(expected_kind) =
792 trait_pred.skip_binder().trait_ref.args.type_at(1).to_opt_closure_kind()
793 && !found_kind.extends(expected_kind)
794 {
795 if let Some((_, Some(parent))) = obligation.cause.code().parent_with_predicate() {
796 trait_pred = parent;
798 } else if let &ObligationCauseCode::FunctionArg { arg_hir_id, .. } =
799 obligation.cause.code()
800 && let Some(typeck_results) = &self.typeck_results
801 && let ty::Closure(closure_def_id, _) | ty::CoroutineClosure(closure_def_id, _) =
802 *typeck_results.node_type(arg_hir_id).kind()
803 {
804 let mut err = self.report_closure_error(
806 &obligation,
807 closure_def_id,
808 found_kind,
809 expected_kind,
810 "Async",
811 );
812 self.note_obligation_cause(&mut err, &obligation);
813 self.point_at_returns_when_relevant(&mut err, &obligation);
814 return Some(err.emit());
815 }
816 }
817
818 let self_ty = trait_pred.self_ty().skip_binder();
819
820 if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) {
821 let (closure_def_id, found_args, by_ref_captures) = match *self_ty.kind() {
822 ty::Closure(def_id, args) => {
823 (def_id, args.as_closure().sig().map_bound(|sig| sig.inputs()[0]), None)
824 }
825 ty::CoroutineClosure(def_id, args) => (
826 def_id,
827 args.as_coroutine_closure()
828 .coroutine_closure_sig()
829 .map_bound(|sig| sig.tupled_inputs_ty),
830 Some(args.as_coroutine_closure().coroutine_captures_by_ref_ty()),
831 ),
832 _ => return None,
833 };
834
835 let expected_args =
836 trait_pred.map_bound(|trait_pred| trait_pred.trait_ref.args.type_at(1));
837
838 if self.enter_forall(found_args, |found_args| {
841 self.enter_forall(expected_args, |expected_args| {
842 !self.can_eq(obligation.param_env, expected_args, found_args)
843 })
844 }) {
845 return None;
846 }
847
848 if let Some(found_kind) = self.closure_kind(self_ty)
849 && !found_kind.extends(expected_kind)
850 {
851 let mut err = self.report_closure_error(
852 &obligation,
853 closure_def_id,
854 found_kind,
855 expected_kind,
856 "",
857 );
858 self.note_obligation_cause(&mut err, &obligation);
859 self.point_at_returns_when_relevant(&mut err, &obligation);
860 return Some(err.emit());
861 }
862
863 if let Some(by_ref_captures) = by_ref_captures
867 && let ty::FnPtr(sig_tys, _) = by_ref_captures.kind()
868 && !sig_tys.skip_binder().output().is_unit()
869 {
870 let mut err = self.dcx().create_err(AsyncClosureNotFn {
871 span: self.tcx.def_span(closure_def_id),
872 kind: expected_kind.as_str(),
873 });
874 self.note_obligation_cause(&mut err, &obligation);
875 self.point_at_returns_when_relevant(&mut err, &obligation);
876 return Some(err.emit());
877 }
878 }
879 None
880 }
881
882 fn fn_arg_obligation(
883 &self,
884 obligation: &PredicateObligation<'tcx>,
885 ) -> Result<(), ErrorGuaranteed> {
886 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
887 && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
888 && let arg = arg.peel_borrows()
889 && let hir::ExprKind::Path(hir::QPath::Resolved(
890 None,
891 hir::Path { res: hir::def::Res::Local(hir_id), .. },
892 )) = arg.kind
893 && let Node::Pat(pat) = self.tcx.hir_node(*hir_id)
894 && let Some((preds, guar)) = self.reported_trait_errors.borrow().get(&pat.span)
895 && preds.contains(&obligation.predicate)
896 {
897 return Err(*guar);
898 }
899 Ok(())
900 }
901
902 fn try_conversion_context(
906 &self,
907 obligation: &PredicateObligation<'tcx>,
908 trait_pred: ty::PolyTraitPredicate<'tcx>,
909 err: &mut Diag<'_>,
910 ) -> bool {
911 let span = obligation.cause.span;
912 struct FindMethodSubexprOfTry {
914 search_span: Span,
915 }
916 impl<'v> Visitor<'v> for FindMethodSubexprOfTry {
917 type Result = ControlFlow<&'v hir::Expr<'v>>;
918 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
919 if let hir::ExprKind::Match(expr, _arms, hir::MatchSource::TryDesugar(_)) = ex.kind
920 && ex.span.with_lo(ex.span.hi() - BytePos(1)).source_equal(self.search_span)
921 && let hir::ExprKind::Call(_, [expr, ..]) = expr.kind
922 {
923 ControlFlow::Break(expr)
924 } else {
925 hir::intravisit::walk_expr(self, ex)
926 }
927 }
928 }
929 let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_id);
930 let Some(body_id) = self.tcx.hir_node(hir_id).body_id() else { return false };
931 let ControlFlow::Break(expr) =
932 (FindMethodSubexprOfTry { search_span: span }).visit_body(self.tcx.hir().body(body_id))
933 else {
934 return false;
935 };
936 let Some(typeck) = &self.typeck_results else {
937 return false;
938 };
939 let Some((ObligationCauseCode::QuestionMark, Some(y))) =
940 obligation.cause.code().parent_with_predicate()
941 else {
942 return false;
943 };
944 if !self.tcx.is_diagnostic_item(sym::FromResidual, y.def_id()) {
945 return false;
946 }
947 let self_ty = trait_pred.skip_binder().self_ty();
948 let found_ty = trait_pred.skip_binder().trait_ref.args.get(1).and_then(|a| a.as_type());
949
950 let mut prev_ty = self.resolve_vars_if_possible(
951 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
952 );
953
954 let get_e_type = |prev_ty: Ty<'tcx>| -> Option<Ty<'tcx>> {
958 let ty::Adt(def, args) = prev_ty.kind() else {
959 return None;
960 };
961 let Some(arg) = args.get(1) else {
962 return None;
963 };
964 if !self.tcx.is_diagnostic_item(sym::Result, def.did()) {
965 return None;
966 }
967 arg.as_type()
968 };
969
970 let mut suggested = false;
971 let mut chain = vec![];
972
973 let mut expr = expr;
975 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
976 expr = rcvr_expr;
980 chain.push((span, prev_ty));
981
982 let next_ty = self.resolve_vars_if_possible(
983 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
984 );
985
986 let is_diagnostic_item = |symbol: Symbol, ty: Ty<'tcx>| {
987 let ty::Adt(def, _) = ty.kind() else {
988 return false;
989 };
990 self.tcx.is_diagnostic_item(symbol, def.did())
991 };
992 if let Some(ty) = get_e_type(prev_ty)
996 && let Some(found_ty) = found_ty
997 && (
1002 ( path_segment.ident.name == sym::map_err
1004 && is_diagnostic_item(sym::Result, next_ty)
1005 ) || ( path_segment.ident.name == sym::ok_or_else
1007 && is_diagnostic_item(sym::Option, next_ty)
1008 )
1009 )
1010 && let ty::Tuple(tys) = found_ty.kind()
1012 && tys.is_empty()
1013 && self.can_eq(obligation.param_env, ty, found_ty)
1015 && let [arg] = args
1017 && let hir::ExprKind::Closure(closure) = arg.kind
1018 && let body = self.tcx.hir().body(closure.body)
1020 && let hir::ExprKind::Block(block, _) = body.value.kind
1021 && let None = block.expr
1022 && let [.., stmt] = block.stmts
1024 && let hir::StmtKind::Semi(expr) = stmt.kind
1025 && let expr_ty = self.resolve_vars_if_possible(
1026 typeck.expr_ty_adjusted_opt(expr)
1027 .unwrap_or(Ty::new_misc_error(self.tcx)),
1028 )
1029 && self
1030 .infcx
1031 .type_implements_trait(
1032 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1033 [self_ty, expr_ty],
1034 obligation.param_env,
1035 )
1036 .must_apply_modulo_regions()
1037 {
1038 suggested = true;
1039 err.span_suggestion_short(
1040 stmt.span.with_lo(expr.span.hi()),
1041 "remove this semicolon",
1042 String::new(),
1043 Applicability::MachineApplicable,
1044 );
1045 }
1046
1047 prev_ty = next_ty;
1048
1049 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1050 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
1051 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
1052 {
1053 let parent = self.tcx.parent_hir_node(binding.hir_id);
1054 if let hir::Node::LetStmt(local) = parent
1056 && let Some(binding_expr) = local.init
1057 {
1058 expr = binding_expr;
1060 }
1061 if let hir::Node::Param(_param) = parent {
1062 break;
1064 }
1065 }
1066 }
1067 prev_ty = self.resolve_vars_if_possible(
1071 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1072 );
1073 chain.push((expr.span, prev_ty));
1074
1075 let mut prev = None;
1076 for (span, err_ty) in chain.into_iter().rev() {
1077 let err_ty = get_e_type(err_ty);
1078 let err_ty = match (err_ty, prev) {
1079 (Some(err_ty), Some(prev)) if !self.can_eq(obligation.param_env, err_ty, prev) => {
1080 err_ty
1081 }
1082 (Some(err_ty), None) => err_ty,
1083 _ => {
1084 prev = err_ty;
1085 continue;
1086 }
1087 };
1088 if self
1089 .infcx
1090 .type_implements_trait(
1091 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1092 [self_ty, err_ty],
1093 obligation.param_env,
1094 )
1095 .must_apply_modulo_regions()
1096 {
1097 if !suggested {
1098 err.span_label(span, format!("this has type `Result<_, {err_ty}>`"));
1099 }
1100 } else {
1101 err.span_label(
1102 span,
1103 format!(
1104 "this can't be annotated with `?` because it has type `Result<_, {err_ty}>`",
1105 ),
1106 );
1107 }
1108 prev = Some(err_ty);
1109 }
1110 suggested
1111 }
1112
1113 fn report_const_param_not_wf(
1114 &self,
1115 ty: Ty<'tcx>,
1116 obligation: &PredicateObligation<'tcx>,
1117 ) -> Diag<'a> {
1118 let span = obligation.cause.span;
1119
1120 let mut diag = match ty.kind() {
1121 _ if ty.has_param() => {
1122 span_bug!(span, "const param tys cannot mention other generic parameters");
1123 }
1124 ty::Float(_) => {
1125 struct_span_code_err!(
1126 self.dcx(),
1127 span,
1128 E0741,
1129 "`{ty}` is forbidden as the type of a const generic parameter",
1130 )
1131 }
1132 ty::FnPtr(..) => {
1133 struct_span_code_err!(
1134 self.dcx(),
1135 span,
1136 E0741,
1137 "using function pointers as const generic parameters is forbidden",
1138 )
1139 }
1140 ty::RawPtr(_, _) => {
1141 struct_span_code_err!(
1142 self.dcx(),
1143 span,
1144 E0741,
1145 "using raw pointers as const generic parameters is forbidden",
1146 )
1147 }
1148 ty::Adt(def, _) => {
1149 let mut diag = struct_span_code_err!(
1151 self.dcx(),
1152 span,
1153 E0741,
1154 "`{ty}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
1155 );
1156 if let Some(span) = self.tcx.hir().span_if_local(def.did())
1159 && obligation.cause.code().parent().is_none()
1160 {
1161 if ty.is_structural_eq_shallow(self.tcx) {
1162 diag.span_suggestion(
1163 span,
1164 "add `#[derive(ConstParamTy)]` to the struct",
1165 "#[derive(ConstParamTy)]\n",
1166 Applicability::MachineApplicable,
1167 );
1168 } else {
1169 diag.span_suggestion(
1172 span,
1173 "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the struct",
1174 "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1175 Applicability::MachineApplicable,
1176 );
1177 }
1178 }
1179 diag
1180 }
1181 _ => {
1182 struct_span_code_err!(
1183 self.dcx(),
1184 span,
1185 E0741,
1186 "`{ty}` can't be used as a const parameter type",
1187 )
1188 }
1189 };
1190
1191 let mut code = obligation.cause.code();
1192 let mut pred = obligation.predicate.as_trait_clause();
1193 while let Some((next_code, next_pred)) = code.parent_with_predicate() {
1194 if let Some(pred) = pred {
1195 self.enter_forall(pred, |pred| {
1196 diag.note(format!(
1197 "`{}` must implement `{}`, but it does not",
1198 pred.self_ty(),
1199 pred.print_modifiers_and_trait_path()
1200 ));
1201 })
1202 }
1203 code = next_code;
1204 pred = next_pred;
1205 }
1206
1207 diag
1208 }
1209}
1210
1211impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
1212 fn can_match_trait(
1213 &self,
1214 goal: ty::TraitPredicate<'tcx>,
1215 assumption: ty::PolyTraitPredicate<'tcx>,
1216 ) -> bool {
1217 if goal.polarity != assumption.polarity() {
1219 return false;
1220 }
1221
1222 let trait_assumption = self.instantiate_binder_with_fresh_vars(
1223 DUMMY_SP,
1224 infer::BoundRegionConversionTime::HigherRankedType,
1225 assumption,
1226 );
1227
1228 self.can_eq(ty::ParamEnv::empty(), goal.trait_ref, trait_assumption.trait_ref)
1229 }
1230
1231 fn can_match_projection(
1232 &self,
1233 goal: ty::ProjectionPredicate<'tcx>,
1234 assumption: ty::PolyProjectionPredicate<'tcx>,
1235 ) -> bool {
1236 let assumption = self.instantiate_binder_with_fresh_vars(
1237 DUMMY_SP,
1238 infer::BoundRegionConversionTime::HigherRankedType,
1239 assumption,
1240 );
1241
1242 let param_env = ty::ParamEnv::empty();
1243 self.can_eq(param_env, goal.projection_term, assumption.projection_term)
1244 && self.can_eq(param_env, goal.term, assumption.term)
1245 }
1246
1247 #[instrument(level = "debug", skip(self), ret)]
1250 pub(super) fn error_implies(
1251 &self,
1252 cond: ty::Predicate<'tcx>,
1253 error: ty::Predicate<'tcx>,
1254 ) -> bool {
1255 if cond == error {
1256 return true;
1257 }
1258
1259 if let Some(error) = error.as_trait_clause() {
1260 self.enter_forall(error, |error| {
1261 elaborate(self.tcx, std::iter::once(cond))
1262 .filter_map(|implied| implied.as_trait_clause())
1263 .any(|implied| self.can_match_trait(error, implied))
1264 })
1265 } else if let Some(error) = error.as_projection_clause() {
1266 self.enter_forall(error, |error| {
1267 elaborate(self.tcx, std::iter::once(cond))
1268 .filter_map(|implied| implied.as_projection_clause())
1269 .any(|implied| self.can_match_projection(error, implied))
1270 })
1271 } else {
1272 false
1273 }
1274 }
1275
1276 #[instrument(level = "debug", skip_all)]
1277 pub(super) fn report_projection_error(
1278 &self,
1279 obligation: &PredicateObligation<'tcx>,
1280 error: &MismatchedProjectionTypes<'tcx>,
1281 ) -> ErrorGuaranteed {
1282 let predicate = self.resolve_vars_if_possible(obligation.predicate);
1283
1284 if let Err(e) = predicate.error_reported() {
1285 return e;
1286 }
1287
1288 self.probe(|_| {
1289 let bound_predicate = predicate.kind();
1294 let (values, err) = match bound_predicate.skip_binder() {
1295 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
1296 let ocx = ObligationCtxt::new(self);
1297
1298 let data = self.instantiate_binder_with_fresh_vars(
1299 obligation.cause.span,
1300 infer::BoundRegionConversionTime::HigherRankedType,
1301 bound_predicate.rebind(data),
1302 );
1303 let unnormalized_term = data.projection_term.to_term(self.tcx);
1304 let normalized_term =
1307 ocx.normalize(&obligation.cause, obligation.param_env, unnormalized_term);
1308
1309 let _ = ocx.select_where_possible();
1315
1316 if let Err(new_err) =
1317 ocx.eq(&obligation.cause, obligation.param_env, data.term, normalized_term)
1318 {
1319 (
1320 Some((
1321 data.projection_term,
1322 self.resolve_vars_if_possible(normalized_term),
1323 data.term,
1324 )),
1325 new_err,
1326 )
1327 } else {
1328 (None, error.err)
1329 }
1330 }
1331 ty::PredicateKind::AliasRelate(lhs, rhs, _) => {
1332 let derive_better_type_error =
1333 |alias_term: ty::AliasTerm<'tcx>, expected_term: ty::Term<'tcx>| {
1334 let ocx = ObligationCtxt::new(self);
1335
1336 let Ok(normalized_term) = ocx.structurally_normalize_term(
1337 &ObligationCause::dummy(),
1338 obligation.param_env,
1339 alias_term.to_term(self.tcx),
1340 ) else {
1341 return None;
1342 };
1343
1344 if let Err(terr) = ocx.eq(
1345 &ObligationCause::dummy(),
1346 obligation.param_env,
1347 expected_term,
1348 normalized_term,
1349 ) {
1350 Some((terr, self.resolve_vars_if_possible(normalized_term)))
1351 } else {
1352 None
1353 }
1354 };
1355
1356 if let Some(lhs) = lhs.to_alias_term()
1357 && let Some((better_type_err, expected_term)) =
1358 derive_better_type_error(lhs, rhs)
1359 {
1360 (
1361 Some((lhs, self.resolve_vars_if_possible(expected_term), rhs)),
1362 better_type_err,
1363 )
1364 } else if let Some(rhs) = rhs.to_alias_term()
1365 && let Some((better_type_err, expected_term)) =
1366 derive_better_type_error(rhs, lhs)
1367 {
1368 (
1369 Some((rhs, self.resolve_vars_if_possible(expected_term), lhs)),
1370 better_type_err,
1371 )
1372 } else {
1373 (None, error.err)
1374 }
1375 }
1376 _ => (None, error.err),
1377 };
1378
1379 let mut file = None;
1380 let (msg, span, closure_span) = values
1381 .and_then(|(predicate, normalized_term, expected_term)| {
1382 self.maybe_detailed_projection_msg(
1383 obligation.cause.span,
1384 predicate,
1385 normalized_term,
1386 expected_term,
1387 &mut file,
1388 )
1389 })
1390 .unwrap_or_else(|| {
1391 (
1392 with_forced_trimmed_paths!(format!(
1393 "type mismatch resolving `{}`",
1394 self.tcx
1395 .short_string(self.resolve_vars_if_possible(predicate), &mut file),
1396 )),
1397 obligation.cause.span,
1398 None,
1399 )
1400 });
1401 let mut diag = struct_span_code_err!(self.dcx(), span, E0271, "{msg}");
1402 *diag.long_ty_path() = file;
1403 if let Some(span) = closure_span {
1404 diag.span_label(span, "this closure");
1421 if !span.overlaps(obligation.cause.span) {
1422 diag.span_label(obligation.cause.span, "closure used here");
1424 }
1425 }
1426
1427 let secondary_span = (|| {
1428 let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1429 predicate.kind().skip_binder()
1430 else {
1431 return None;
1432 };
1433
1434 let trait_assoc_item = self.tcx.opt_associated_item(proj.projection_term.def_id)?;
1435 let trait_assoc_ident = trait_assoc_item.ident(self.tcx);
1436
1437 let mut associated_items = vec![];
1438 self.tcx.for_each_relevant_impl(
1439 self.tcx.trait_of_item(proj.projection_term.def_id)?,
1440 proj.projection_term.self_ty(),
1441 |impl_def_id| {
1442 associated_items.extend(
1443 self.tcx
1444 .associated_items(impl_def_id)
1445 .in_definition_order()
1446 .find(|assoc| assoc.ident(self.tcx) == trait_assoc_ident),
1447 );
1448 },
1449 );
1450
1451 let [associated_item]: &[ty::AssocItem] = &associated_items[..] else {
1452 return None;
1453 };
1454 match self.tcx.hir().get_if_local(associated_item.def_id) {
1455 Some(
1456 hir::Node::TraitItem(hir::TraitItem {
1457 kind: hir::TraitItemKind::Type(_, Some(ty)),
1458 ..
1459 })
1460 | hir::Node::ImplItem(hir::ImplItem {
1461 kind: hir::ImplItemKind::Type(ty),
1462 ..
1463 }),
1464 ) => Some((
1465 ty.span,
1466 with_forced_trimmed_paths!(Cow::from(format!(
1467 "type mismatch resolving `{}`",
1468 self.tcx.short_string(
1469 self.resolve_vars_if_possible(predicate),
1470 diag.long_ty_path()
1471 ),
1472 ))),
1473 true,
1474 )),
1475 _ => None,
1476 }
1477 })();
1478
1479 self.note_type_err(
1480 &mut diag,
1481 &obligation.cause,
1482 secondary_span,
1483 values.map(|(_, normalized_ty, expected_ty)| {
1484 obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(
1485 expected_ty,
1486 normalized_ty,
1487 )))
1488 }),
1489 err,
1490 false,
1491 Some(span),
1492 );
1493 self.note_obligation_cause(&mut diag, obligation);
1494 diag.emit()
1495 })
1496 }
1497
1498 fn maybe_detailed_projection_msg(
1499 &self,
1500 mut span: Span,
1501 projection_term: ty::AliasTerm<'tcx>,
1502 normalized_ty: ty::Term<'tcx>,
1503 expected_ty: ty::Term<'tcx>,
1504 file: &mut Option<PathBuf>,
1505 ) -> Option<(String, Span, Option<Span>)> {
1506 let trait_def_id = projection_term.trait_def_id(self.tcx);
1507 let self_ty = projection_term.self_ty();
1508
1509 with_forced_trimmed_paths! {
1510 if self.tcx.is_lang_item(projection_term.def_id, LangItem::FnOnceOutput) {
1511 let (span, closure_span) = if let ty::Closure(def_id, _) = self_ty.kind() {
1512 let def_span = self.tcx.def_span(def_id);
1513 if let Some(local_def_id) = def_id.as_local()
1514 && let node = self.tcx.hir_node_by_def_id(local_def_id)
1515 && let Some(fn_decl) = node.fn_decl()
1516 && let Some(id) = node.body_id()
1517 {
1518 span = match fn_decl.output {
1519 hir::FnRetTy::Return(ty) => ty.span,
1520 hir::FnRetTy::DefaultReturn(_) => {
1521 let body = self.tcx.hir().body(id);
1522 match body.value.kind {
1523 hir::ExprKind::Block(
1524 hir::Block { expr: Some(expr), .. },
1525 _,
1526 ) => expr.span,
1527 hir::ExprKind::Block(
1528 hir::Block {
1529 expr: None, stmts: [.., last], ..
1530 },
1531 _,
1532 ) => last.span,
1533 _ => body.value.span,
1534 }
1535 }
1536 };
1537 }
1538 (span, Some(def_span))
1539 } else {
1540 (span, None)
1541 };
1542 let item = match self_ty.kind() {
1543 ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
1544 _ => self.tcx.short_string(self_ty, file),
1545 };
1546 Some((format!(
1547 "expected `{item}` to return `{expected_ty}`, but it returns `{normalized_ty}`",
1548 ), span, closure_span))
1549 } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
1550 Some((format!(
1551 "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
1552 resolves to `{normalized_ty}`"
1553 ), span, None))
1554 } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
1555 Some((format!(
1556 "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
1557 yields `{normalized_ty}`"
1558 ), span, None))
1559 } else {
1560 None
1561 }
1562 }
1563 }
1564
1565 pub fn fuzzy_match_tys(
1566 &self,
1567 mut a: Ty<'tcx>,
1568 mut b: Ty<'tcx>,
1569 ignoring_lifetimes: bool,
1570 ) -> Option<CandidateSimilarity> {
1571 fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
1574 match t.kind() {
1575 ty::Bool => Some(0),
1576 ty::Char => Some(1),
1577 ty::Str => Some(2),
1578 ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => Some(2),
1579 ty::Int(..)
1580 | ty::Uint(..)
1581 | ty::Float(..)
1582 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
1583 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1584 ty::Array(..) | ty::Slice(..) => Some(6),
1585 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1586 ty::Dynamic(..) => Some(8),
1587 ty::Closure(..) => Some(9),
1588 ty::Tuple(..) => Some(10),
1589 ty::Param(..) => Some(11),
1590 ty::Alias(ty::Projection, ..) => Some(12),
1591 ty::Alias(ty::Inherent, ..) => Some(13),
1592 ty::Alias(ty::Opaque, ..) => Some(14),
1593 ty::Alias(ty::Weak, ..) => Some(15),
1594 ty::Never => Some(16),
1595 ty::Adt(..) => Some(17),
1596 ty::Coroutine(..) => Some(18),
1597 ty::Foreign(..) => Some(19),
1598 ty::CoroutineWitness(..) => Some(20),
1599 ty::CoroutineClosure(..) => Some(21),
1600 ty::Pat(..) => Some(22),
1601 ty::UnsafeBinder(..) => Some(23),
1602 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1603 }
1604 }
1605
1606 let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
1607 loop {
1608 match t.kind() {
1609 ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => t = *inner,
1610 _ => break t,
1611 }
1612 }
1613 };
1614
1615 if !ignoring_lifetimes {
1616 a = strip_references(a);
1617 b = strip_references(b);
1618 }
1619
1620 let cat_a = type_category(self.tcx, a)?;
1621 let cat_b = type_category(self.tcx, b)?;
1622 if a == b {
1623 Some(CandidateSimilarity::Exact { ignoring_lifetimes })
1624 } else if cat_a == cat_b {
1625 match (a.kind(), b.kind()) {
1626 (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
1627 (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
1628 (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
1634 self.fuzzy_match_tys(a, b, true).is_some()
1635 }
1636 _ => true,
1637 }
1638 .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
1639 } else if ignoring_lifetimes {
1640 None
1641 } else {
1642 self.fuzzy_match_tys(a, b, true)
1643 }
1644 }
1645
1646 pub(super) fn describe_closure(&self, kind: hir::ClosureKind) -> &'static str {
1647 match kind {
1648 hir::ClosureKind::Closure => "a closure",
1649 hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => "a coroutine",
1650 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1651 hir::CoroutineDesugaring::Async,
1652 hir::CoroutineSource::Block,
1653 )) => "an async block",
1654 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1655 hir::CoroutineDesugaring::Async,
1656 hir::CoroutineSource::Fn,
1657 )) => "an async function",
1658 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1659 hir::CoroutineDesugaring::Async,
1660 hir::CoroutineSource::Closure,
1661 ))
1662 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
1663 "an async closure"
1664 }
1665 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1666 hir::CoroutineDesugaring::AsyncGen,
1667 hir::CoroutineSource::Block,
1668 )) => "an async gen block",
1669 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1670 hir::CoroutineDesugaring::AsyncGen,
1671 hir::CoroutineSource::Fn,
1672 )) => "an async gen function",
1673 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1674 hir::CoroutineDesugaring::AsyncGen,
1675 hir::CoroutineSource::Closure,
1676 ))
1677 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
1678 "an async gen closure"
1679 }
1680 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1681 hir::CoroutineDesugaring::Gen,
1682 hir::CoroutineSource::Block,
1683 )) => "a gen block",
1684 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1685 hir::CoroutineDesugaring::Gen,
1686 hir::CoroutineSource::Fn,
1687 )) => "a gen function",
1688 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1689 hir::CoroutineDesugaring::Gen,
1690 hir::CoroutineSource::Closure,
1691 ))
1692 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => "a gen closure",
1693 }
1694 }
1695
1696 pub(super) fn find_similar_impl_candidates(
1697 &self,
1698 trait_pred: ty::PolyTraitPredicate<'tcx>,
1699 ) -> Vec<ImplCandidate<'tcx>> {
1700 let mut candidates: Vec<_> = self
1701 .tcx
1702 .all_impls(trait_pred.def_id())
1703 .filter_map(|def_id| {
1704 let imp = self.tcx.impl_trait_header(def_id).unwrap();
1705 if imp.polarity != ty::ImplPolarity::Positive
1706 || !self.tcx.is_user_visible_dep(def_id.krate)
1707 {
1708 return None;
1709 }
1710 let imp = imp.trait_ref.skip_binder();
1711
1712 self.fuzzy_match_tys(trait_pred.skip_binder().self_ty(), imp.self_ty(), false).map(
1713 |similarity| ImplCandidate { trait_ref: imp, similarity, impl_def_id: def_id },
1714 )
1715 })
1716 .collect();
1717 if candidates.iter().any(|c| matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
1718 candidates.retain(|c| matches!(c.similarity, CandidateSimilarity::Exact { .. }));
1722 }
1723 candidates
1724 }
1725
1726 pub(super) fn report_similar_impl_candidates(
1727 &self,
1728 impl_candidates: &[ImplCandidate<'tcx>],
1729 trait_pred: ty::PolyTraitPredicate<'tcx>,
1730 body_def_id: LocalDefId,
1731 err: &mut Diag<'_>,
1732 other: bool,
1733 param_env: ty::ParamEnv<'tcx>,
1734 ) -> bool {
1735 let alternative_candidates = |def_id: DefId| {
1736 let mut impl_candidates: Vec<_> = self
1737 .tcx
1738 .all_impls(def_id)
1739 .filter(|def_id| !self.tcx.do_not_recommend_impl(*def_id))
1741 .filter_map(|def_id| self.tcx.impl_trait_header(def_id))
1743 .filter_map(|header| {
1744 (header.polarity != ty::ImplPolarity::Negative
1745 || self.tcx.is_automatically_derived(def_id))
1746 .then(|| header.trait_ref.instantiate_identity())
1747 })
1748 .filter(|trait_ref| {
1749 let self_ty = trait_ref.self_ty();
1750 if let ty::Param(_) = self_ty.kind() {
1752 false
1753 }
1754 else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
1756 self.tcx.visibility(def.did()).is_accessible_from(body_def_id, self.tcx)
1760 } else {
1761 true
1762 }
1763 })
1764 .collect();
1765
1766 impl_candidates.sort_by_key(|tr| tr.to_string());
1767 impl_candidates.dedup();
1768 impl_candidates
1769 };
1770
1771 let trait_def_id = trait_pred.def_id();
1775 let trait_name = self.tcx.item_name(trait_def_id);
1776 let crate_name = self.tcx.crate_name(trait_def_id.krate);
1777 if let Some(other_trait_def_id) = self.tcx.all_traits().find(|def_id| {
1778 trait_name == self.tcx.item_name(trait_def_id)
1779 && trait_def_id.krate != def_id.krate
1780 && crate_name == self.tcx.crate_name(def_id.krate)
1781 }) {
1782 let found_type =
1786 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind() {
1787 Some(def.did())
1788 } else {
1789 None
1790 };
1791 let candidates = if impl_candidates.is_empty() {
1792 alternative_candidates(trait_def_id)
1793 } else {
1794 impl_candidates.into_iter().map(|cand| cand.trait_ref).collect()
1795 };
1796 let mut span: MultiSpan = self.tcx.def_span(trait_def_id).into();
1797 span.push_span_label(self.tcx.def_span(trait_def_id), "this is the required trait");
1798 for (sp, label) in [trait_def_id, other_trait_def_id]
1799 .iter()
1800 .filter(|def_id| !def_id.is_local())
1804 .filter_map(|def_id| self.tcx.extern_crate(def_id.krate))
1805 .map(|data| {
1806 let dependency = if data.dependency_of == LOCAL_CRATE {
1807 "direct dependency of the current crate".to_string()
1808 } else {
1809 let dep = self.tcx.crate_name(data.dependency_of);
1810 format!("dependency of crate `{dep}`")
1811 };
1812 (
1813 data.span,
1814 format!("one version of crate `{crate_name}` used here, as a {dependency}"),
1815 )
1816 })
1817 {
1818 span.push_span_label(sp, label);
1819 }
1820 let mut points_at_type = false;
1821 if let Some(found_type) = found_type {
1822 span.push_span_label(
1823 self.tcx.def_span(found_type),
1824 "this type doesn't implement the required trait",
1825 );
1826 for trait_ref in candidates {
1827 if let ty::Adt(def, _) = trait_ref.self_ty().peel_refs().kind()
1828 && let candidate_def_id = def.did()
1829 && let Some(name) = self.tcx.opt_item_name(candidate_def_id)
1830 && let Some(found) = self.tcx.opt_item_name(found_type)
1831 && name == found
1832 && candidate_def_id.krate != found_type.krate
1833 && self.tcx.crate_name(candidate_def_id.krate)
1834 == self.tcx.crate_name(found_type.krate)
1835 {
1836 let candidate_span = self.tcx.def_span(candidate_def_id);
1839 span.push_span_label(
1840 candidate_span,
1841 "this type implements the required trait",
1842 );
1843 points_at_type = true;
1844 }
1845 }
1846 }
1847 span.push_span_label(self.tcx.def_span(other_trait_def_id), "this is the found trait");
1848 err.highlighted_span_note(
1849 span,
1850 vec![
1851 StringPart::normal("there are ".to_string()),
1852 StringPart::highlighted("multiple different versions".to_string()),
1853 StringPart::normal(" of crate `".to_string()),
1854 StringPart::highlighted(format!("{crate_name}")),
1855 StringPart::normal("` in the dependency graph\n".to_string()),
1856 ],
1857 );
1858 if points_at_type {
1859 err.highlighted_note(vec![
1864 StringPart::normal(
1865 "two types coming from two different versions of the same crate are \
1866 different types "
1867 .to_string(),
1868 ),
1869 StringPart::highlighted("even if they look the same".to_string()),
1870 ]);
1871 }
1872 err.highlighted_help(vec![
1873 StringPart::normal("you can use `".to_string()),
1874 StringPart::highlighted("cargo tree".to_string()),
1875 StringPart::normal("` to explore your dependency tree".to_string()),
1876 ]);
1877 return true;
1878 }
1879
1880 if let [single] = &impl_candidates {
1881 if self.probe(|_| {
1884 let ocx = ObligationCtxt::new(self);
1885
1886 self.enter_forall(trait_pred, |obligation_trait_ref| {
1887 let impl_args = self.fresh_args_for_item(DUMMY_SP, single.impl_def_id);
1888 let impl_trait_ref = ocx.normalize(
1889 &ObligationCause::dummy(),
1890 param_env,
1891 ty::EarlyBinder::bind(single.trait_ref).instantiate(self.tcx, impl_args),
1892 );
1893
1894 ocx.register_obligations(
1895 self.tcx
1896 .predicates_of(single.impl_def_id)
1897 .instantiate(self.tcx, impl_args)
1898 .into_iter()
1899 .map(|(clause, _)| {
1900 Obligation::new(
1901 self.tcx,
1902 ObligationCause::dummy(),
1903 param_env,
1904 clause,
1905 )
1906 }),
1907 );
1908 if !ocx.select_where_possible().is_empty() {
1909 return false;
1910 }
1911
1912 let mut terrs = vec![];
1913 for (obligation_arg, impl_arg) in
1914 std::iter::zip(obligation_trait_ref.trait_ref.args, impl_trait_ref.args)
1915 {
1916 if (obligation_arg, impl_arg).references_error() {
1917 return false;
1918 }
1919 if let Err(terr) =
1920 ocx.eq(&ObligationCause::dummy(), param_env, impl_arg, obligation_arg)
1921 {
1922 terrs.push(terr);
1923 }
1924 if !ocx.select_where_possible().is_empty() {
1925 return false;
1926 }
1927 }
1928
1929 if terrs.len() == impl_trait_ref.args.len() {
1931 return false;
1932 }
1933
1934 let impl_trait_ref = self.resolve_vars_if_possible(impl_trait_ref);
1935 if impl_trait_ref.references_error() {
1936 return false;
1937 }
1938
1939 if let [child, ..] = &err.children[..]
1940 && child.level == Level::Help
1941 && let Some(line) = child.messages.get(0)
1942 && let Some(line) = line.0.as_str()
1943 && line.starts_with("the trait")
1944 && line.contains("is not implemented for")
1945 {
1946 err.children.remove(0);
1953 }
1954
1955 let traits = self.cmp_traits(
1956 obligation_trait_ref.def_id(),
1957 &obligation_trait_ref.trait_ref.args[1..],
1958 impl_trait_ref.def_id,
1959 &impl_trait_ref.args[1..],
1960 );
1961 let traits_content = (traits.0.content(), traits.1.content());
1962 let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty());
1963 let types_content = (types.0.content(), types.1.content());
1964 let mut msg = vec![StringPart::normal("the trait `")];
1965 if traits_content.0 == traits_content.1 {
1966 msg.push(StringPart::normal(
1967 impl_trait_ref.print_trait_sugared().to_string(),
1968 ));
1969 } else {
1970 msg.extend(traits.0.0);
1971 }
1972 msg.extend([
1973 StringPart::normal("` "),
1974 StringPart::highlighted("is not"),
1975 StringPart::normal(" implemented for `"),
1976 ]);
1977 if types_content.0 == types_content.1 {
1978 let ty = self
1979 .tcx
1980 .short_string(obligation_trait_ref.self_ty(), err.long_ty_path());
1981 msg.push(StringPart::normal(ty));
1982 } else {
1983 msg.extend(types.0.0);
1984 }
1985 msg.push(StringPart::normal("`"));
1986 if types_content.0 == types_content.1 {
1987 msg.push(StringPart::normal("\nbut trait `"));
1988 msg.extend(traits.1.0);
1989 msg.extend([
1990 StringPart::normal("` "),
1991 StringPart::highlighted("is"),
1992 StringPart::normal(" implemented for it"),
1993 ]);
1994 } else if traits_content.0 == traits_content.1 {
1995 msg.extend([
1996 StringPart::normal("\nbut it "),
1997 StringPart::highlighted("is"),
1998 StringPart::normal(" implemented for `"),
1999 ]);
2000 msg.extend(types.1.0);
2001 msg.push(StringPart::normal("`"));
2002 } else {
2003 msg.push(StringPart::normal("\nbut trait `"));
2004 msg.extend(traits.1.0);
2005 msg.extend([
2006 StringPart::normal("` "),
2007 StringPart::highlighted("is"),
2008 StringPart::normal(" implemented for `"),
2009 ]);
2010 msg.extend(types.1.0);
2011 msg.push(StringPart::normal("`"));
2012 }
2013 err.highlighted_help(msg);
2014
2015 if let [TypeError::Sorts(exp_found)] = &terrs[..] {
2016 let exp_found = self.resolve_vars_if_possible(*exp_found);
2017 err.highlighted_help(vec![
2018 StringPart::normal("for that trait implementation, "),
2019 StringPart::normal("expected `"),
2020 StringPart::highlighted(exp_found.expected.to_string()),
2021 StringPart::normal("`, found `"),
2022 StringPart::highlighted(exp_found.found.to_string()),
2023 StringPart::normal("`"),
2024 ]);
2025 self.suggest_function_pointers_impl(None, &exp_found, err);
2026 }
2027
2028 true
2029 })
2030 }) {
2031 return true;
2032 }
2033 }
2034
2035 let other = if other { "other " } else { "" };
2036 let report = |mut candidates: Vec<TraitRef<'tcx>>, err: &mut Diag<'_>| {
2037 candidates.retain(|tr| !tr.references_error());
2038 if candidates.is_empty() {
2039 return false;
2040 }
2041 if let &[cand] = &candidates[..] {
2042 let (desc, mention_castable) =
2043 match (cand.self_ty().kind(), trait_pred.self_ty().skip_binder().kind()) {
2044 (ty::FnPtr(..), ty::FnDef(..)) => {
2045 (" implemented for fn pointer `", ", cast using `as`")
2046 }
2047 (ty::FnPtr(..), _) => (" implemented for fn pointer `", ""),
2048 _ => (" implemented for `", ""),
2049 };
2050 err.highlighted_help(vec![
2051 StringPart::normal(format!("the trait `{}` ", cand.print_trait_sugared())),
2052 StringPart::highlighted("is"),
2053 StringPart::normal(desc),
2054 StringPart::highlighted(cand.self_ty().to_string()),
2055 StringPart::normal("`"),
2056 StringPart::normal(mention_castable),
2057 ]);
2058 return true;
2059 }
2060 let trait_ref = TraitRef::identity(self.tcx, candidates[0].def_id);
2061 let mut traits: Vec<_> =
2063 candidates.iter().map(|c| c.print_only_trait_path().to_string()).collect();
2064 traits.sort();
2065 traits.dedup();
2066 let all_traits_equal = traits.len() == 1;
2069
2070 let candidates: Vec<String> = candidates
2071 .into_iter()
2072 .map(|c| {
2073 if all_traits_equal {
2074 format!("\n {}", c.self_ty())
2075 } else {
2076 format!("\n `{}` implements `{}`", c.self_ty(), c.print_only_trait_path())
2077 }
2078 })
2079 .collect();
2080
2081 let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose {
2082 candidates.len()
2083 } else {
2084 8
2085 };
2086 err.help(format!(
2087 "the following {other}types implement trait `{}`:{}{}",
2088 trait_ref.print_trait_sugared(),
2089 candidates[..end].join(""),
2090 if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
2091 format!("\nand {} others", candidates.len() - 8)
2092 } else {
2093 String::new()
2094 }
2095 ));
2096 true
2097 };
2098
2099 let impl_candidates = impl_candidates
2102 .into_iter()
2103 .cloned()
2104 .filter(|cand| !self.tcx.do_not_recommend_impl(cand.impl_def_id))
2105 .collect::<Vec<_>>();
2106
2107 let def_id = trait_pred.def_id();
2108 if impl_candidates.is_empty() {
2109 if self.tcx.trait_is_auto(def_id)
2110 || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2111 || self.tcx.get_diagnostic_name(def_id).is_some()
2112 {
2113 return false;
2115 }
2116 return report(alternative_candidates(def_id), err);
2117 }
2118
2119 let mut impl_candidates: Vec<_> = impl_candidates
2126 .iter()
2127 .cloned()
2128 .filter(|cand| !cand.trait_ref.references_error())
2129 .map(|mut cand| {
2130 cand.trait_ref = self
2134 .tcx
2135 .try_normalize_erasing_regions(
2136 ty::TypingEnv::non_body_analysis(self.tcx, cand.impl_def_id),
2137 cand.trait_ref,
2138 )
2139 .unwrap_or(cand.trait_ref);
2140 cand
2141 })
2142 .collect();
2143 impl_candidates.sort_by_key(|cand| (cand.similarity, cand.trait_ref.to_string()));
2144 let mut impl_candidates: Vec<_> =
2145 impl_candidates.into_iter().map(|cand| cand.trait_ref).collect();
2146 impl_candidates.dedup();
2147
2148 report(impl_candidates, err)
2149 }
2150
2151 fn report_similar_impl_candidates_for_root_obligation(
2152 &self,
2153 obligation: &PredicateObligation<'tcx>,
2154 trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2155 body_def_id: LocalDefId,
2156 err: &mut Diag<'_>,
2157 ) {
2158 let mut code = obligation.cause.code();
2165 let mut trait_pred = trait_predicate;
2166 let mut peeled = false;
2167 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
2168 code = parent_code;
2169 if let Some(parent_trait_pred) = parent_trait_pred {
2170 trait_pred = parent_trait_pred;
2171 peeled = true;
2172 }
2173 }
2174 let def_id = trait_pred.def_id();
2175 if peeled
2181 && !self.tcx.trait_is_auto(def_id)
2182 && !self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2183 {
2184 let impl_candidates = self.find_similar_impl_candidates(trait_pred);
2185 self.report_similar_impl_candidates(
2186 &impl_candidates,
2187 trait_pred,
2188 body_def_id,
2189 err,
2190 true,
2191 obligation.param_env,
2192 );
2193 }
2194 }
2195
2196 fn get_parent_trait_ref(
2198 &self,
2199 code: &ObligationCauseCode<'tcx>,
2200 ) -> Option<(Ty<'tcx>, Option<Span>)> {
2201 match code {
2202 ObligationCauseCode::BuiltinDerived(data) => {
2203 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2204 match self.get_parent_trait_ref(&data.parent_code) {
2205 Some(t) => Some(t),
2206 None => {
2207 let ty = parent_trait_ref.skip_binder().self_ty();
2208 let span = TyCategory::from_ty(self.tcx, ty)
2209 .map(|(_, def_id)| self.tcx.def_span(def_id));
2210 Some((ty, span))
2211 }
2212 }
2213 }
2214 ObligationCauseCode::FunctionArg { parent_code, .. } => {
2215 self.get_parent_trait_ref(parent_code)
2216 }
2217 _ => None,
2218 }
2219 }
2220
2221 fn note_version_mismatch(
2225 &self,
2226 err: &mut Diag<'_>,
2227 trait_pred: ty::PolyTraitPredicate<'tcx>,
2228 ) -> bool {
2229 let get_trait_impls = |trait_def_id| {
2230 let mut trait_impls = vec![];
2231 self.tcx.for_each_relevant_impl(
2232 trait_def_id,
2233 trait_pred.skip_binder().self_ty(),
2234 |impl_def_id| {
2235 trait_impls.push(impl_def_id);
2236 },
2237 );
2238 trait_impls
2239 };
2240
2241 let required_trait_path = self.tcx.def_path_str(trait_pred.def_id());
2242 let traits_with_same_path: UnordSet<_> = self
2243 .tcx
2244 .visible_traits()
2245 .filter(|trait_def_id| *trait_def_id != trait_pred.def_id())
2246 .map(|trait_def_id| (self.tcx.def_path_str(trait_def_id), trait_def_id))
2247 .filter(|(p, _)| *p == required_trait_path)
2248 .collect();
2249
2250 let traits_with_same_path =
2251 traits_with_same_path.into_items().into_sorted_stable_ord_by_key(|(p, _)| p);
2252 let mut suggested = false;
2253 for (_, trait_with_same_path) in traits_with_same_path {
2254 let trait_impls = get_trait_impls(trait_with_same_path);
2255 if trait_impls.is_empty() {
2256 continue;
2257 }
2258 let impl_spans: Vec<_> =
2259 trait_impls.iter().map(|impl_def_id| self.tcx.def_span(*impl_def_id)).collect();
2260 err.span_help(
2261 impl_spans,
2262 format!("trait impl{} with same name found", pluralize!(trait_impls.len())),
2263 );
2264 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
2265 let crate_msg =
2266 format!("perhaps two different versions of crate `{trait_crate}` are being used?");
2267 err.note(crate_msg);
2268 suggested = true;
2269 }
2270 suggested
2271 }
2272
2273 pub(super) fn mk_trait_obligation_with_new_self_ty(
2278 &self,
2279 param_env: ty::ParamEnv<'tcx>,
2280 trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
2281 ) -> PredicateObligation<'tcx> {
2282 let trait_pred =
2283 trait_ref_and_ty.map_bound(|(tr, new_self_ty)| tr.with_self_ty(self.tcx, new_self_ty));
2284
2285 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
2286 }
2287
2288 fn predicate_can_apply(
2291 &self,
2292 param_env: ty::ParamEnv<'tcx>,
2293 pred: ty::PolyTraitPredicate<'tcx>,
2294 ) -> bool {
2295 struct ParamToVarFolder<'a, 'tcx> {
2296 infcx: &'a InferCtxt<'tcx>,
2297 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2298 }
2299
2300 impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
2301 fn cx(&self) -> TyCtxt<'tcx> {
2302 self.infcx.tcx
2303 }
2304
2305 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2306 if let ty::Param(_) = *ty.kind() {
2307 let infcx = self.infcx;
2308 *self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
2309 } else {
2310 ty.super_fold_with(self)
2311 }
2312 }
2313 }
2314
2315 self.probe(|_| {
2316 let cleaned_pred =
2317 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2318
2319 let InferOk { value: cleaned_pred, .. } =
2320 self.infcx.at(&ObligationCause::dummy(), param_env).normalize(cleaned_pred);
2321
2322 let obligation =
2323 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
2324
2325 self.predicate_may_hold(&obligation)
2326 })
2327 }
2328
2329 pub fn note_obligation_cause(
2330 &self,
2331 err: &mut Diag<'_>,
2332 obligation: &PredicateObligation<'tcx>,
2333 ) {
2334 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2337 self.note_obligation_cause_code(
2338 obligation.cause.body_id,
2339 err,
2340 obligation.predicate,
2341 obligation.param_env,
2342 obligation.cause.code(),
2343 &mut vec![],
2344 &mut Default::default(),
2345 );
2346 self.suggest_unsized_bound_if_applicable(err, obligation);
2347 if let Some(span) = err.span.primary_span()
2348 && let Some(mut diag) =
2349 self.dcx().steal_non_err(span, StashKey::AssociatedTypeSuggestion)
2350 && let Suggestions::Enabled(ref mut s1) = err.suggestions
2351 && let Suggestions::Enabled(ref mut s2) = diag.suggestions
2352 {
2353 s1.append(s2);
2354 diag.cancel()
2355 }
2356 }
2357 }
2358
2359 pub(super) fn is_recursive_obligation(
2360 &self,
2361 obligated_types: &mut Vec<Ty<'tcx>>,
2362 cause_code: &ObligationCauseCode<'tcx>,
2363 ) -> bool {
2364 if let ObligationCauseCode::BuiltinDerived(ref data) = cause_code {
2365 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2366 let self_ty = parent_trait_ref.skip_binder().self_ty();
2367 if obligated_types.iter().any(|ot| ot == &self_ty) {
2368 return true;
2369 }
2370 if let ty::Adt(def, args) = self_ty.kind()
2371 && let [arg] = &args[..]
2372 && let ty::GenericArgKind::Type(ty) = arg.unpack()
2373 && let ty::Adt(inner_def, _) = ty.kind()
2374 && inner_def == def
2375 {
2376 return true;
2377 }
2378 }
2379 false
2380 }
2381
2382 fn get_standard_error_message(
2383 &self,
2384 trait_predicate: ty::PolyTraitPredicate<'tcx>,
2385 message: Option<String>,
2386 predicate_constness: Option<ty::BoundConstness>,
2387 append_const_msg: Option<AppendConstMessage>,
2388 post_message: String,
2389 long_ty_file: &mut Option<PathBuf>,
2390 ) -> String {
2391 message
2392 .and_then(|cannot_do_this| {
2393 match (predicate_constness, append_const_msg) {
2394 (None, _) => Some(cannot_do_this),
2396 (
2398 Some(ty::BoundConstness::Const | ty::BoundConstness::Maybe),
2399 Some(AppendConstMessage::Default),
2400 ) => Some(format!("{cannot_do_this} in const contexts")),
2401 (
2403 Some(ty::BoundConstness::Const | ty::BoundConstness::Maybe),
2404 Some(AppendConstMessage::Custom(custom_msg, _)),
2405 ) => Some(format!("{cannot_do_this}{custom_msg}")),
2406 (Some(ty::BoundConstness::Const | ty::BoundConstness::Maybe), None) => None,
2408 }
2409 })
2410 .unwrap_or_else(|| {
2411 format!(
2412 "the trait bound `{}` is not satisfied{post_message}",
2413 self.tcx.short_string(
2414 trait_predicate.print_with_bound_constness(predicate_constness),
2415 long_ty_file,
2416 ),
2417 )
2418 })
2419 }
2420
2421 fn get_safe_transmute_error_and_reason(
2422 &self,
2423 obligation: PredicateObligation<'tcx>,
2424 trait_pred: ty::PolyTraitPredicate<'tcx>,
2425 span: Span,
2426 ) -> GetSafeTransmuteErrorAndReason {
2427 use rustc_transmute::Answer;
2428 self.probe(|_| {
2429 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
2432 return GetSafeTransmuteErrorAndReason::Default;
2433 }
2434
2435 let trait_pred =
2437 self.tcx.erase_regions(self.tcx.instantiate_bound_regions_with_erased(trait_pred));
2438
2439 let src_and_dst = rustc_transmute::Types {
2440 dst: trait_pred.trait_ref.args.type_at(0),
2441 src: trait_pred.trait_ref.args.type_at(1),
2442 };
2443
2444 let ocx = ObligationCtxt::new(self);
2445 let Ok(assume) = ocx.structurally_normalize_const(
2446 &obligation.cause,
2447 obligation.param_env,
2448 trait_pred.trait_ref.args.const_at(2),
2449 ) else {
2450 self.dcx().span_delayed_bug(
2451 span,
2452 "Unable to construct rustc_transmute::Assume where it was previously possible",
2453 );
2454 return GetSafeTransmuteErrorAndReason::Silent;
2455 };
2456
2457 let Some(assume) =
2458 rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, assume)
2459 else {
2460 self.dcx().span_delayed_bug(
2461 span,
2462 "Unable to construct rustc_transmute::Assume where it was previously possible",
2463 );
2464 return GetSafeTransmuteErrorAndReason::Silent;
2465 };
2466
2467 let dst = trait_pred.trait_ref.args.type_at(0);
2468 let src = trait_pred.trait_ref.args.type_at(1);
2469 let err_msg = format!("`{src}` cannot be safely transmuted into `{dst}`");
2470
2471 match rustc_transmute::TransmuteTypeEnv::new(self.infcx).is_transmutable(
2472 obligation.cause,
2473 src_and_dst,
2474 assume,
2475 ) {
2476 Answer::No(reason) => {
2477 let safe_transmute_explanation = match reason {
2478 rustc_transmute::Reason::SrcIsNotYetSupported => {
2479 format!("analyzing the transmutability of `{src}` is not yet supported")
2480 }
2481
2482 rustc_transmute::Reason::DstIsNotYetSupported => {
2483 format!("analyzing the transmutability of `{dst}` is not yet supported")
2484 }
2485
2486 rustc_transmute::Reason::DstIsBitIncompatible => {
2487 format!(
2488 "at least one value of `{src}` isn't a bit-valid value of `{dst}`"
2489 )
2490 }
2491
2492 rustc_transmute::Reason::DstUninhabited => {
2493 format!("`{dst}` is uninhabited")
2494 }
2495
2496 rustc_transmute::Reason::DstMayHaveSafetyInvariants => {
2497 format!("`{dst}` may carry safety invariants")
2498 }
2499 rustc_transmute::Reason::DstIsTooBig => {
2500 format!("the size of `{src}` is smaller than the size of `{dst}`")
2501 }
2502 rustc_transmute::Reason::DstRefIsTooBig { src, dst } => {
2503 let src_size = src.size;
2504 let dst_size = dst.size;
2505 format!(
2506 "the referent size of `{src}` ({src_size} bytes) \
2507 is smaller than that of `{dst}` ({dst_size} bytes)"
2508 )
2509 }
2510 rustc_transmute::Reason::SrcSizeOverflow => {
2511 format!(
2512 "values of the type `{src}` are too big for the target architecture"
2513 )
2514 }
2515 rustc_transmute::Reason::DstSizeOverflow => {
2516 format!(
2517 "values of the type `{dst}` are too big for the target architecture"
2518 )
2519 }
2520 rustc_transmute::Reason::DstHasStricterAlignment {
2521 src_min_align,
2522 dst_min_align,
2523 } => {
2524 format!(
2525 "the minimum alignment of `{src}` ({src_min_align}) should \
2526 be greater than that of `{dst}` ({dst_min_align})"
2527 )
2528 }
2529 rustc_transmute::Reason::DstIsMoreUnique => {
2530 format!(
2531 "`{src}` is a shared reference, but `{dst}` is a unique reference"
2532 )
2533 }
2534 rustc_transmute::Reason::TypeError => {
2536 return GetSafeTransmuteErrorAndReason::Silent;
2537 }
2538 rustc_transmute::Reason::SrcLayoutUnknown => {
2539 format!("`{src}` has an unknown layout")
2540 }
2541 rustc_transmute::Reason::DstLayoutUnknown => {
2542 format!("`{dst}` has an unknown layout")
2543 }
2544 };
2545 GetSafeTransmuteErrorAndReason::Error {
2546 err_msg,
2547 safe_transmute_explanation: Some(safe_transmute_explanation),
2548 }
2549 }
2550 Answer::Yes => span_bug!(
2552 span,
2553 "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
2554 ),
2555 Answer::If(_) => GetSafeTransmuteErrorAndReason::Error {
2560 err_msg,
2561 safe_transmute_explanation: None,
2562 },
2563 }
2564 })
2565 }
2566
2567 fn add_tuple_trait_message(
2568 &self,
2569 obligation_cause_code: &ObligationCauseCode<'tcx>,
2570 err: &mut Diag<'_>,
2571 ) {
2572 match obligation_cause_code {
2573 ObligationCauseCode::RustCall => {
2574 err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
2575 }
2576 ObligationCauseCode::WhereClause(def_id, _) if self.tcx.is_fn_trait(*def_id) => {
2577 err.code(E0059);
2578 err.primary_message(format!(
2579 "type parameter to bare `{}` trait must be a tuple",
2580 self.tcx.def_path_str(*def_id)
2581 ));
2582 }
2583 _ => {}
2584 }
2585 }
2586
2587 fn try_to_add_help_message(
2588 &self,
2589 root_obligation: &PredicateObligation<'tcx>,
2590 obligation: &PredicateObligation<'tcx>,
2591 trait_predicate: ty::PolyTraitPredicate<'tcx>,
2592 err: &mut Diag<'_>,
2593 span: Span,
2594 is_fn_trait: bool,
2595 suggested: bool,
2596 unsatisfied_const: bool,
2597 ) {
2598 let body_def_id = obligation.cause.body_id;
2599 let span = if let ObligationCauseCode::BinOp { rhs_span: Some(rhs_span), .. } =
2600 obligation.cause.code()
2601 {
2602 *rhs_span
2603 } else {
2604 span
2605 };
2606
2607 let trait_def_id = trait_predicate.def_id();
2609 if is_fn_trait
2610 && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
2611 obligation.param_env,
2612 trait_predicate.self_ty(),
2613 trait_predicate.skip_binder().polarity,
2614 )
2615 {
2616 self.add_help_message_for_fn_trait(trait_predicate, err, implemented_kind, params);
2617 } else if !trait_predicate.has_non_region_infer()
2618 && self.predicate_can_apply(obligation.param_env, trait_predicate)
2619 {
2620 self.suggest_restricting_param_bound(
2628 err,
2629 trait_predicate,
2630 None,
2631 obligation.cause.body_id,
2632 );
2633 } else if trait_def_id.is_local()
2634 && self.tcx.trait_impls_of(trait_def_id).is_empty()
2635 && !self.tcx.trait_is_auto(trait_def_id)
2636 && !self.tcx.trait_is_alias(trait_def_id)
2637 && trait_predicate.polarity() == ty::PredicatePolarity::Positive
2638 {
2639 err.span_help(
2640 self.tcx.def_span(trait_def_id),
2641 crate::fluent_generated::trait_selection_trait_has_no_impls,
2642 );
2643 } else if !suggested
2644 && !unsatisfied_const
2645 && trait_predicate.polarity() == ty::PredicatePolarity::Positive
2646 {
2647 let impl_candidates = self.find_similar_impl_candidates(trait_predicate);
2649 if !self.report_similar_impl_candidates(
2650 &impl_candidates,
2651 trait_predicate,
2652 body_def_id,
2653 err,
2654 true,
2655 obligation.param_env,
2656 ) {
2657 self.report_similar_impl_candidates_for_root_obligation(
2658 obligation,
2659 trait_predicate,
2660 body_def_id,
2661 err,
2662 );
2663 }
2664
2665 self.suggest_convert_to_slice(
2666 err,
2667 obligation,
2668 trait_predicate,
2669 impl_candidates.as_slice(),
2670 span,
2671 );
2672
2673 self.suggest_tuple_wrapping(err, root_obligation, obligation);
2674 }
2675 }
2676
2677 fn add_help_message_for_fn_trait(
2678 &self,
2679 trait_pred: ty::PolyTraitPredicate<'tcx>,
2680 err: &mut Diag<'_>,
2681 implemented_kind: ty::ClosureKind,
2682 params: ty::Binder<'tcx, Ty<'tcx>>,
2683 ) {
2684 let selected_kind = self
2691 .tcx
2692 .fn_trait_kind_from_def_id(trait_pred.def_id())
2693 .expect("expected to map DefId to ClosureKind");
2694 if !implemented_kind.extends(selected_kind) {
2695 err.note(format!(
2696 "`{}` implements `{}`, but it must implement `{}`, which is more general",
2697 trait_pred.skip_binder().self_ty(),
2698 implemented_kind,
2699 selected_kind
2700 ));
2701 }
2702
2703 let given_ty = params.skip_binder();
2705 let expected_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
2706 if let ty::Tuple(given) = given_ty.kind()
2707 && let ty::Tuple(expected) = expected_ty.kind()
2708 {
2709 if expected.len() != given.len() {
2710 err.note(
2712 format!(
2713 "expected a closure taking {} argument{}, but one taking {} argument{} was given",
2714 given.len(),
2715 pluralize!(given.len()),
2716 expected.len(),
2717 pluralize!(expected.len()),
2718 )
2719 );
2720 } else if !self.same_type_modulo_infer(given_ty, expected_ty) {
2721 let (expected_args, given_args) = self.cmp(given_ty, expected_ty);
2723 err.note_expected_found(
2724 &"a closure with arguments",
2725 expected_args,
2726 &"a closure with arguments",
2727 given_args,
2728 );
2729 }
2730 }
2731 }
2732
2733 fn maybe_add_note_for_unsatisfied_const(
2734 &self,
2735 _trait_predicate: ty::PolyTraitPredicate<'tcx>,
2736 _err: &mut Diag<'_>,
2737 _span: Span,
2738 ) -> UnsatisfiedConst {
2739 let unsatisfied_const = UnsatisfiedConst(false);
2740 unsatisfied_const
2742 }
2743
2744 fn report_closure_error(
2745 &self,
2746 obligation: &PredicateObligation<'tcx>,
2747 closure_def_id: DefId,
2748 found_kind: ty::ClosureKind,
2749 kind: ty::ClosureKind,
2750 trait_prefix: &'static str,
2751 ) -> Diag<'a> {
2752 let closure_span = self.tcx.def_span(closure_def_id);
2753
2754 let mut err = ClosureKindMismatch {
2755 closure_span,
2756 expected: kind,
2757 found: found_kind,
2758 cause_span: obligation.cause.span,
2759 trait_prefix,
2760 fn_once_label: None,
2761 fn_mut_label: None,
2762 };
2763
2764 if let Some(typeck_results) = &self.typeck_results {
2767 let hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id.expect_local());
2768 match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
2769 (ty::ClosureKind::FnOnce, Some((span, place))) => {
2770 err.fn_once_label = Some(ClosureFnOnceLabel {
2771 span: *span,
2772 place: ty::place_to_string_for_capture(self.tcx, place),
2773 })
2774 }
2775 (ty::ClosureKind::FnMut, Some((span, place))) => {
2776 err.fn_mut_label = Some(ClosureFnMutLabel {
2777 span: *span,
2778 place: ty::place_to_string_for_capture(self.tcx, place),
2779 })
2780 }
2781 _ => {}
2782 }
2783 }
2784
2785 self.dcx().create_err(err)
2786 }
2787
2788 fn report_cyclic_signature_error(
2789 &self,
2790 obligation: &PredicateObligation<'tcx>,
2791 found_trait_ref: ty::TraitRef<'tcx>,
2792 expected_trait_ref: ty::TraitRef<'tcx>,
2793 terr: TypeError<'tcx>,
2794 ) -> Diag<'a> {
2795 let self_ty = found_trait_ref.self_ty();
2796 let (cause, terr) = if let ty::Closure(def_id, _) = self_ty.kind() {
2797 (
2798 ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
2799 TypeError::CyclicTy(self_ty),
2800 )
2801 } else {
2802 (obligation.cause.clone(), terr)
2803 };
2804 self.report_and_explain_type_error(
2805 TypeTrace::trait_refs(&cause, expected_trait_ref, found_trait_ref),
2806 obligation.param_env,
2807 terr,
2808 )
2809 }
2810
2811 fn report_opaque_type_auto_trait_leakage(
2812 &self,
2813 obligation: &PredicateObligation<'tcx>,
2814 def_id: DefId,
2815 ) -> ErrorGuaranteed {
2816 let name = match self.tcx.local_opaque_ty_origin(def_id.expect_local()) {
2817 hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } => {
2818 "opaque type".to_string()
2819 }
2820 hir::OpaqueTyOrigin::TyAlias { .. } => {
2821 format!("`{}`", self.tcx.def_path_debug_str(def_id))
2822 }
2823 };
2824 let mut err = self.dcx().struct_span_err(
2825 obligation.cause.span,
2826 format!("cannot check whether the hidden type of {name} satisfies auto traits"),
2827 );
2828
2829 err.note(
2830 "fetching the hidden types of an opaque inside of the defining scope is not supported. \
2831 You can try moving the opaque type and the item that actually registers a hidden type into a new submodule",
2832 );
2833 err.span_note(self.tcx.def_span(def_id), "opaque type is declared here");
2834
2835 self.note_obligation_cause(&mut err, &obligation);
2836 self.point_at_returns_when_relevant(&mut err, &obligation);
2837 self.dcx().try_steal_replace_and_emit_err(self.tcx.def_span(def_id), StashKey::Cycle, err)
2838 }
2839
2840 fn report_signature_mismatch_error(
2841 &self,
2842 obligation: &PredicateObligation<'tcx>,
2843 span: Span,
2844 found_trait_ref: ty::TraitRef<'tcx>,
2845 expected_trait_ref: ty::TraitRef<'tcx>,
2846 ) -> Result<Diag<'a>, ErrorGuaranteed> {
2847 let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
2848 let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
2849
2850 expected_trait_ref.self_ty().error_reported()?;
2851 let found_trait_ty = found_trait_ref.self_ty();
2852
2853 let found_did = match *found_trait_ty.kind() {
2854 ty::Closure(did, _) | ty::FnDef(did, _) | ty::Coroutine(did, ..) => Some(did),
2855 _ => None,
2856 };
2857
2858 let found_node = found_did.and_then(|did| self.tcx.hir().get_if_local(did));
2859 let found_span = found_did.and_then(|did| self.tcx.hir().span_if_local(did));
2860
2861 if !self.reported_signature_mismatch.borrow_mut().insert((span, found_span)) {
2862 return Err(self.dcx().span_delayed_bug(span, "already_reported"));
2865 }
2866
2867 let mut not_tupled = false;
2868
2869 let found = match found_trait_ref.args.type_at(1).kind() {
2870 ty::Tuple(tys) => vec![ArgKind::empty(); tys.len()],
2871 _ => {
2872 not_tupled = true;
2873 vec![ArgKind::empty()]
2874 }
2875 };
2876
2877 let expected_ty = expected_trait_ref.args.type_at(1);
2878 let expected = match expected_ty.kind() {
2879 ty::Tuple(tys) => {
2880 tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
2881 }
2882 _ => {
2883 not_tupled = true;
2884 vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())]
2885 }
2886 };
2887
2888 if Some(expected_trait_ref.def_id) != self.tcx.lang_items().coroutine_trait() && not_tupled
2894 {
2895 return Ok(self.report_and_explain_type_error(
2896 TypeTrace::trait_refs(&obligation.cause, expected_trait_ref, found_trait_ref),
2897 obligation.param_env,
2898 ty::error::TypeError::Mismatch,
2899 ));
2900 }
2901 if found.len() != expected.len() {
2902 let (closure_span, closure_arg_span, found) = found_did
2903 .and_then(|did| {
2904 let node = self.tcx.hir().get_if_local(did)?;
2905 let (found_span, closure_arg_span, found) = self.get_fn_like_arguments(node)?;
2906 Some((Some(found_span), closure_arg_span, found))
2907 })
2908 .unwrap_or((found_span, None, found));
2909
2910 if found.len() != expected.len() {
2916 return Ok(self.report_arg_count_mismatch(
2917 span,
2918 closure_span,
2919 expected,
2920 found,
2921 found_trait_ty.is_closure(),
2922 closure_arg_span,
2923 ));
2924 }
2925 }
2926 Ok(self.report_closure_arg_mismatch(
2927 span,
2928 found_span,
2929 found_trait_ref,
2930 expected_trait_ref,
2931 obligation.cause.code(),
2932 found_node,
2933 obligation.param_env,
2934 ))
2935 }
2936
2937 pub fn get_fn_like_arguments(
2942 &self,
2943 node: Node<'_>,
2944 ) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
2945 let sm = self.tcx.sess.source_map();
2946 let hir = self.tcx.hir();
2947 Some(match node {
2948 Node::Expr(&hir::Expr {
2949 kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
2950 ..
2951 }) => (
2952 fn_decl_span,
2953 fn_arg_span,
2954 hir.body(body)
2955 .params
2956 .iter()
2957 .map(|arg| {
2958 if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat
2959 {
2960 Some(ArgKind::Tuple(
2961 Some(span),
2962 args.iter()
2963 .map(|pat| {
2964 sm.span_to_snippet(pat.span)
2965 .ok()
2966 .map(|snippet| (snippet, "_".to_owned()))
2967 })
2968 .collect::<Option<Vec<_>>>()?,
2969 ))
2970 } else {
2971 let name = sm.span_to_snippet(arg.pat.span).ok()?;
2972 Some(ArgKind::Arg(name, "_".to_owned()))
2973 }
2974 })
2975 .collect::<Option<Vec<ArgKind>>>()?,
2976 ),
2977 Node::Item(&hir::Item { kind: hir::ItemKind::Fn { ref sig, .. }, .. })
2978 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
2979 | Node::TraitItem(&hir::TraitItem {
2980 kind: hir::TraitItemKind::Fn(ref sig, _), ..
2981 })
2982 | Node::ForeignItem(&hir::ForeignItem {
2983 kind: hir::ForeignItemKind::Fn(ref sig, _, _),
2984 ..
2985 }) => (
2986 sig.span,
2987 None,
2988 sig.decl
2989 .inputs
2990 .iter()
2991 .map(|arg| match arg.kind {
2992 hir::TyKind::Tup(tys) => ArgKind::Tuple(
2993 Some(arg.span),
2994 vec![("_".to_owned(), "_".to_owned()); tys.len()],
2995 ),
2996 _ => ArgKind::empty(),
2997 })
2998 .collect::<Vec<ArgKind>>(),
2999 ),
3000 Node::Ctor(variant_data) => {
3001 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id));
3002 (span, None, vec![ArgKind::empty(); variant_data.fields().len()])
3003 }
3004 _ => panic!("non-FnLike node found: {node:?}"),
3005 })
3006 }
3007
3008 pub fn report_arg_count_mismatch(
3012 &self,
3013 span: Span,
3014 found_span: Option<Span>,
3015 expected_args: Vec<ArgKind>,
3016 found_args: Vec<ArgKind>,
3017 is_closure: bool,
3018 closure_arg_span: Option<Span>,
3019 ) -> Diag<'a> {
3020 let kind = if is_closure { "closure" } else { "function" };
3021
3022 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
3023 let arg_length = arguments.len();
3024 let distinct = matches!(other, &[ArgKind::Tuple(..)]);
3025 match (arg_length, arguments.get(0)) {
3026 (1, Some(ArgKind::Tuple(_, fields))) => {
3027 format!("a single {}-tuple as argument", fields.len())
3028 }
3029 _ => format!(
3030 "{} {}argument{}",
3031 arg_length,
3032 if distinct && arg_length > 1 { "distinct " } else { "" },
3033 pluralize!(arg_length)
3034 ),
3035 }
3036 };
3037
3038 let expected_str = args_str(&expected_args, &found_args);
3039 let found_str = args_str(&found_args, &expected_args);
3040
3041 let mut err = struct_span_code_err!(
3042 self.dcx(),
3043 span,
3044 E0593,
3045 "{} is expected to take {}, but it takes {}",
3046 kind,
3047 expected_str,
3048 found_str,
3049 );
3050
3051 err.span_label(span, format!("expected {kind} that takes {expected_str}"));
3052
3053 if let Some(found_span) = found_span {
3054 err.span_label(found_span, format!("takes {found_str}"));
3055
3056 if found_args.is_empty() && is_closure {
3060 let underscores = vec!["_"; expected_args.len()].join(", ");
3061 err.span_suggestion_verbose(
3062 closure_arg_span.unwrap_or(found_span),
3063 format!(
3064 "consider changing the closure to take and ignore the expected argument{}",
3065 pluralize!(expected_args.len())
3066 ),
3067 format!("|{underscores}|"),
3068 Applicability::MachineApplicable,
3069 );
3070 }
3071
3072 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
3073 if fields.len() == expected_args.len() {
3074 let sugg = fields
3075 .iter()
3076 .map(|(name, _)| name.to_owned())
3077 .collect::<Vec<String>>()
3078 .join(", ");
3079 err.span_suggestion_verbose(
3080 found_span,
3081 "change the closure to take multiple arguments instead of a single tuple",
3082 format!("|{sugg}|"),
3083 Applicability::MachineApplicable,
3084 );
3085 }
3086 }
3087 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
3088 && fields.len() == found_args.len()
3089 && is_closure
3090 {
3091 let sugg = format!(
3092 "|({}){}|",
3093 found_args
3094 .iter()
3095 .map(|arg| match arg {
3096 ArgKind::Arg(name, _) => name.to_owned(),
3097 _ => "_".to_owned(),
3098 })
3099 .collect::<Vec<String>>()
3100 .join(", "),
3101 if found_args.iter().any(|arg| match arg {
3103 ArgKind::Arg(_, ty) => ty != "_",
3104 _ => false,
3105 }) {
3106 format!(
3107 ": ({})",
3108 fields
3109 .iter()
3110 .map(|(_, ty)| ty.to_owned())
3111 .collect::<Vec<String>>()
3112 .join(", ")
3113 )
3114 } else {
3115 String::new()
3116 },
3117 );
3118 err.span_suggestion_verbose(
3119 found_span,
3120 "change the closure to accept a tuple instead of individual arguments",
3121 sugg,
3122 Applicability::MachineApplicable,
3123 );
3124 }
3125 }
3126
3127 err
3128 }
3129
3130 pub fn type_implements_fn_trait(
3134 &self,
3135 param_env: ty::ParamEnv<'tcx>,
3136 ty: ty::Binder<'tcx, Ty<'tcx>>,
3137 polarity: ty::PredicatePolarity,
3138 ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
3139 self.commit_if_ok(|_| {
3140 for trait_def_id in [
3141 self.tcx.lang_items().fn_trait(),
3142 self.tcx.lang_items().fn_mut_trait(),
3143 self.tcx.lang_items().fn_once_trait(),
3144 ] {
3145 let Some(trait_def_id) = trait_def_id else { continue };
3146 let var = self.next_ty_var(DUMMY_SP);
3149 let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
3151 let obligation = Obligation::new(
3152 self.tcx,
3153 ObligationCause::dummy(),
3154 param_env,
3155 ty.rebind(ty::TraitPredicate { trait_ref, polarity }),
3156 );
3157 let ocx = ObligationCtxt::new(self);
3158 ocx.register_obligation(obligation);
3159 if ocx.select_all_or_error().is_empty() {
3160 return Ok((
3161 self.tcx
3162 .fn_trait_kind_from_def_id(trait_def_id)
3163 .expect("expected to map DefId to ClosureKind"),
3164 ty.rebind(self.resolve_vars_if_possible(var)),
3165 ));
3166 }
3167 }
3168
3169 Err(())
3170 })
3171 }
3172
3173 fn report_not_const_evaluatable_error(
3174 &self,
3175 obligation: &PredicateObligation<'tcx>,
3176 span: Span,
3177 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3178 if !self.tcx.features().generic_const_exprs() {
3179 let guar = self
3180 .dcx()
3181 .struct_span_err(span, "constant expression depends on a generic parameter")
3182 .with_note("this may fail depending on what value the parameter takes")
3189 .emit();
3190 return Err(guar);
3191 }
3192
3193 match obligation.predicate.kind().skip_binder() {
3194 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => match ct.kind() {
3195 ty::ConstKind::Unevaluated(uv) => {
3196 let mut err =
3197 self.dcx().struct_span_err(span, "unconstrained generic constant");
3198 let const_span = self.tcx.def_span(uv.def);
3199
3200 let const_ty = self.tcx.type_of(uv.def).instantiate(self.tcx, uv.args);
3201 let cast = if const_ty != self.tcx.types.usize { " as usize" } else { "" };
3202 let msg = "try adding a `where` bound";
3203 match self.tcx.sess.source_map().span_to_snippet(const_span) {
3204 Ok(snippet) => {
3205 let code = format!("[(); {snippet}{cast}]:");
3206 let def_id = if let ObligationCauseCode::CompareImplItem {
3207 trait_item_def_id,
3208 ..
3209 } = obligation.cause.code()
3210 {
3211 trait_item_def_id.as_local()
3212 } else {
3213 Some(obligation.cause.body_id)
3214 };
3215 if let Some(def_id) = def_id
3216 && let Some(generics) = self.tcx.hir().get_generics(def_id)
3217 {
3218 err.span_suggestion_verbose(
3219 generics.tail_span_for_predicate_suggestion(),
3220 msg,
3221 format!("{} {code}", generics.add_where_or_trailing_comma()),
3222 Applicability::MaybeIncorrect,
3223 );
3224 } else {
3225 err.help(format!("{msg}: where {code}"));
3226 };
3227 }
3228 _ => {
3229 err.help(msg);
3230 }
3231 };
3232 Ok(err)
3233 }
3234 ty::ConstKind::Expr(_) => {
3235 let err = self
3236 .dcx()
3237 .struct_span_err(span, format!("unconstrained generic constant `{ct}`"));
3238 Ok(err)
3239 }
3240 _ => {
3241 bug!("const evaluatable failed for non-unevaluated const `{ct:?}`");
3242 }
3243 },
3244 _ => {
3245 span_bug!(
3246 span,
3247 "unexpected non-ConstEvaluatable predicate, this should not be reachable"
3248 )
3249 }
3250 }
3251 }
3252}