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 err.emit()
711 }
712}
713
714impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
715 pub(super) fn apply_do_not_recommend(
716 &self,
717 obligation: &mut PredicateObligation<'tcx>,
718 ) -> bool {
719 let mut base_cause = obligation.cause.code().clone();
720 let mut applied_do_not_recommend = false;
721 loop {
722 if let ObligationCauseCode::ImplDerived(ref c) = base_cause {
723 if self.tcx.do_not_recommend_impl(c.impl_or_alias_def_id) {
724 let code = (*c.derived.parent_code).clone();
725 obligation.cause.map_code(|_| code);
726 obligation.predicate = c.derived.parent_trait_pred.upcast(self.tcx);
727 applied_do_not_recommend = true;
728 }
729 }
730 if let Some(parent_cause) = base_cause.parent() {
731 base_cause = parent_cause.clone();
732 } else {
733 break;
734 }
735 }
736
737 applied_do_not_recommend
738 }
739
740 fn report_host_effect_error(
741 &self,
742 predicate: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
743 param_env: ty::ParamEnv<'tcx>,
744 span: Span,
745 ) -> Diag<'a> {
746 let trait_ref = predicate.map_bound(|predicate| ty::TraitPredicate {
753 trait_ref: predicate.trait_ref,
754 polarity: ty::PredicatePolarity::Positive,
755 });
756 let mut file = None;
757 let err_msg = self.get_standard_error_message(
758 trait_ref,
759 None,
760 Some(predicate.constness()),
761 None,
762 String::new(),
763 &mut file,
764 );
765 let mut diag = struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg);
766 *diag.long_ty_path() = file;
767 if !self.predicate_may_hold(&Obligation::new(
768 self.tcx,
769 ObligationCause::dummy(),
770 param_env,
771 trait_ref,
772 )) {
773 diag.downgrade_to_delayed_bug();
774 }
775 diag
776 }
777
778 fn emit_specialized_closure_kind_error(
779 &self,
780 obligation: &PredicateObligation<'tcx>,
781 mut trait_pred: ty::PolyTraitPredicate<'tcx>,
782 ) -> Option<ErrorGuaranteed> {
783 if self.tcx.is_lang_item(trait_pred.def_id(), LangItem::AsyncFnKindHelper)
788 && let Some(found_kind) =
789 trait_pred.skip_binder().trait_ref.args.type_at(0).to_opt_closure_kind()
790 && let Some(expected_kind) =
791 trait_pred.skip_binder().trait_ref.args.type_at(1).to_opt_closure_kind()
792 && !found_kind.extends(expected_kind)
793 {
794 if let Some((_, Some(parent))) = obligation.cause.code().parent_with_predicate() {
795 trait_pred = parent;
797 } else if let &ObligationCauseCode::FunctionArg { arg_hir_id, .. } =
798 obligation.cause.code()
799 && let Some(typeck_results) = &self.typeck_results
800 && let ty::Closure(closure_def_id, _) | ty::CoroutineClosure(closure_def_id, _) =
801 *typeck_results.node_type(arg_hir_id).kind()
802 {
803 let mut err = self.report_closure_error(
805 &obligation,
806 closure_def_id,
807 found_kind,
808 expected_kind,
809 "Async",
810 );
811 self.note_obligation_cause(&mut err, &obligation);
812 return Some(err.emit());
813 }
814 }
815
816 let self_ty = trait_pred.self_ty().skip_binder();
817
818 if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) {
819 let (closure_def_id, found_args, by_ref_captures) = match *self_ty.kind() {
820 ty::Closure(def_id, args) => {
821 (def_id, args.as_closure().sig().map_bound(|sig| sig.inputs()[0]), None)
822 }
823 ty::CoroutineClosure(def_id, args) => (
824 def_id,
825 args.as_coroutine_closure()
826 .coroutine_closure_sig()
827 .map_bound(|sig| sig.tupled_inputs_ty),
828 Some(args.as_coroutine_closure().coroutine_captures_by_ref_ty()),
829 ),
830 _ => return None,
831 };
832
833 let expected_args =
834 trait_pred.map_bound(|trait_pred| trait_pred.trait_ref.args.type_at(1));
835
836 if self.enter_forall(found_args, |found_args| {
839 self.enter_forall(expected_args, |expected_args| {
840 !self.can_eq(obligation.param_env, expected_args, found_args)
841 })
842 }) {
843 return None;
844 }
845
846 if let Some(found_kind) = self.closure_kind(self_ty)
847 && !found_kind.extends(expected_kind)
848 {
849 let mut err = self.report_closure_error(
850 &obligation,
851 closure_def_id,
852 found_kind,
853 expected_kind,
854 "",
855 );
856 self.note_obligation_cause(&mut err, &obligation);
857 return Some(err.emit());
858 }
859
860 if let Some(by_ref_captures) = by_ref_captures
864 && let ty::FnPtr(sig_tys, _) = by_ref_captures.kind()
865 && !sig_tys.skip_binder().output().is_unit()
866 {
867 let mut err = self.dcx().create_err(AsyncClosureNotFn {
868 span: self.tcx.def_span(closure_def_id),
869 kind: expected_kind.as_str(),
870 });
871 self.note_obligation_cause(&mut err, &obligation);
872 return Some(err.emit());
873 }
874 }
875 None
876 }
877
878 fn fn_arg_obligation(
879 &self,
880 obligation: &PredicateObligation<'tcx>,
881 ) -> Result<(), ErrorGuaranteed> {
882 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
883 && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
884 && let arg = arg.peel_borrows()
885 && let hir::ExprKind::Path(hir::QPath::Resolved(
886 None,
887 hir::Path { res: hir::def::Res::Local(hir_id), .. },
888 )) = arg.kind
889 && let Node::Pat(pat) = self.tcx.hir_node(*hir_id)
890 && let Some((preds, guar)) = self.reported_trait_errors.borrow().get(&pat.span)
891 && preds.contains(&obligation.predicate)
892 {
893 return Err(*guar);
894 }
895 Ok(())
896 }
897
898 fn try_conversion_context(
902 &self,
903 obligation: &PredicateObligation<'tcx>,
904 trait_pred: ty::PolyTraitPredicate<'tcx>,
905 err: &mut Diag<'_>,
906 ) -> bool {
907 let span = obligation.cause.span;
908 struct FindMethodSubexprOfTry {
910 search_span: Span,
911 }
912 impl<'v> Visitor<'v> for FindMethodSubexprOfTry {
913 type Result = ControlFlow<&'v hir::Expr<'v>>;
914 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
915 if let hir::ExprKind::Match(expr, _arms, hir::MatchSource::TryDesugar(_)) = ex.kind
916 && ex.span.with_lo(ex.span.hi() - BytePos(1)).source_equal(self.search_span)
917 && let hir::ExprKind::Call(_, [expr, ..]) = expr.kind
918 {
919 ControlFlow::Break(expr)
920 } else {
921 hir::intravisit::walk_expr(self, ex)
922 }
923 }
924 }
925 let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_id);
926 let Some(body_id) = self.tcx.hir_node(hir_id).body_id() else { return false };
927 let ControlFlow::Break(expr) =
928 (FindMethodSubexprOfTry { search_span: span }).visit_body(self.tcx.hir().body(body_id))
929 else {
930 return false;
931 };
932 let Some(typeck) = &self.typeck_results else {
933 return false;
934 };
935 let Some((ObligationCauseCode::QuestionMark, Some(y))) =
936 obligation.cause.code().parent_with_predicate()
937 else {
938 return false;
939 };
940 if !self.tcx.is_diagnostic_item(sym::FromResidual, y.def_id()) {
941 return false;
942 }
943 let self_ty = trait_pred.skip_binder().self_ty();
944 let found_ty = trait_pred.skip_binder().trait_ref.args.get(1).and_then(|a| a.as_type());
945
946 let mut prev_ty = self.resolve_vars_if_possible(
947 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
948 );
949
950 let get_e_type = |prev_ty: Ty<'tcx>| -> Option<Ty<'tcx>> {
954 let ty::Adt(def, args) = prev_ty.kind() else {
955 return None;
956 };
957 let Some(arg) = args.get(1) else {
958 return None;
959 };
960 if !self.tcx.is_diagnostic_item(sym::Result, def.did()) {
961 return None;
962 }
963 arg.as_type()
964 };
965
966 let mut suggested = false;
967 let mut chain = vec![];
968
969 let mut expr = expr;
971 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
972 expr = rcvr_expr;
976 chain.push((span, prev_ty));
977
978 let next_ty = self.resolve_vars_if_possible(
979 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
980 );
981
982 let is_diagnostic_item = |symbol: Symbol, ty: Ty<'tcx>| {
983 let ty::Adt(def, _) = ty.kind() else {
984 return false;
985 };
986 self.tcx.is_diagnostic_item(symbol, def.did())
987 };
988 if let Some(ty) = get_e_type(prev_ty)
992 && let Some(found_ty) = found_ty
993 && (
998 ( path_segment.ident.name == sym::map_err
1000 && is_diagnostic_item(sym::Result, next_ty)
1001 ) || ( path_segment.ident.name == sym::ok_or_else
1003 && is_diagnostic_item(sym::Option, next_ty)
1004 )
1005 )
1006 && let ty::Tuple(tys) = found_ty.kind()
1008 && tys.is_empty()
1009 && self.can_eq(obligation.param_env, ty, found_ty)
1011 && let [arg] = args
1013 && let hir::ExprKind::Closure(closure) = arg.kind
1014 && let body = self.tcx.hir().body(closure.body)
1016 && let hir::ExprKind::Block(block, _) = body.value.kind
1017 && let None = block.expr
1018 && let [.., stmt] = block.stmts
1020 && let hir::StmtKind::Semi(expr) = stmt.kind
1021 && let expr_ty = self.resolve_vars_if_possible(
1022 typeck.expr_ty_adjusted_opt(expr)
1023 .unwrap_or(Ty::new_misc_error(self.tcx)),
1024 )
1025 && self
1026 .infcx
1027 .type_implements_trait(
1028 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1029 [self_ty, expr_ty],
1030 obligation.param_env,
1031 )
1032 .must_apply_modulo_regions()
1033 {
1034 suggested = true;
1035 err.span_suggestion_short(
1036 stmt.span.with_lo(expr.span.hi()),
1037 "remove this semicolon",
1038 String::new(),
1039 Applicability::MachineApplicable,
1040 );
1041 }
1042
1043 prev_ty = next_ty;
1044
1045 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1046 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
1047 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
1048 {
1049 let parent = self.tcx.parent_hir_node(binding.hir_id);
1050 if let hir::Node::LetStmt(local) = parent
1052 && let Some(binding_expr) = local.init
1053 {
1054 expr = binding_expr;
1056 }
1057 if let hir::Node::Param(_param) = parent {
1058 break;
1060 }
1061 }
1062 }
1063 prev_ty = self.resolve_vars_if_possible(
1067 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1068 );
1069 chain.push((expr.span, prev_ty));
1070
1071 let mut prev = None;
1072 for (span, err_ty) in chain.into_iter().rev() {
1073 let err_ty = get_e_type(err_ty);
1074 let err_ty = match (err_ty, prev) {
1075 (Some(err_ty), Some(prev)) if !self.can_eq(obligation.param_env, err_ty, prev) => {
1076 err_ty
1077 }
1078 (Some(err_ty), None) => err_ty,
1079 _ => {
1080 prev = err_ty;
1081 continue;
1082 }
1083 };
1084 if self
1085 .infcx
1086 .type_implements_trait(
1087 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1088 [self_ty, err_ty],
1089 obligation.param_env,
1090 )
1091 .must_apply_modulo_regions()
1092 {
1093 if !suggested {
1094 err.span_label(span, format!("this has type `Result<_, {err_ty}>`"));
1095 }
1096 } else {
1097 err.span_label(
1098 span,
1099 format!(
1100 "this can't be annotated with `?` because it has type `Result<_, {err_ty}>`",
1101 ),
1102 );
1103 }
1104 prev = Some(err_ty);
1105 }
1106 suggested
1107 }
1108
1109 fn report_const_param_not_wf(
1110 &self,
1111 ty: Ty<'tcx>,
1112 obligation: &PredicateObligation<'tcx>,
1113 ) -> Diag<'a> {
1114 let span = obligation.cause.span;
1115
1116 let mut diag = match ty.kind() {
1117 _ if ty.has_param() => {
1118 span_bug!(span, "const param tys cannot mention other generic parameters");
1119 }
1120 ty::Float(_) => {
1121 struct_span_code_err!(
1122 self.dcx(),
1123 span,
1124 E0741,
1125 "`{ty}` is forbidden as the type of a const generic parameter",
1126 )
1127 }
1128 ty::FnPtr(..) => {
1129 struct_span_code_err!(
1130 self.dcx(),
1131 span,
1132 E0741,
1133 "using function pointers as const generic parameters is forbidden",
1134 )
1135 }
1136 ty::RawPtr(_, _) => {
1137 struct_span_code_err!(
1138 self.dcx(),
1139 span,
1140 E0741,
1141 "using raw pointers as const generic parameters is forbidden",
1142 )
1143 }
1144 ty::Adt(def, _) => {
1145 let mut diag = struct_span_code_err!(
1147 self.dcx(),
1148 span,
1149 E0741,
1150 "`{ty}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
1151 );
1152 if let Some(span) = self.tcx.hir().span_if_local(def.did())
1155 && obligation.cause.code().parent().is_none()
1156 {
1157 if ty.is_structural_eq_shallow(self.tcx) {
1158 diag.span_suggestion(
1159 span,
1160 "add `#[derive(ConstParamTy)]` to the struct",
1161 "#[derive(ConstParamTy)]\n",
1162 Applicability::MachineApplicable,
1163 );
1164 } else {
1165 diag.span_suggestion(
1168 span,
1169 "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the struct",
1170 "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1171 Applicability::MachineApplicable,
1172 );
1173 }
1174 }
1175 diag
1176 }
1177 _ => {
1178 struct_span_code_err!(
1179 self.dcx(),
1180 span,
1181 E0741,
1182 "`{ty}` can't be used as a const parameter type",
1183 )
1184 }
1185 };
1186
1187 let mut code = obligation.cause.code();
1188 let mut pred = obligation.predicate.as_trait_clause();
1189 while let Some((next_code, next_pred)) = code.parent_with_predicate() {
1190 if let Some(pred) = pred {
1191 self.enter_forall(pred, |pred| {
1192 diag.note(format!(
1193 "`{}` must implement `{}`, but it does not",
1194 pred.self_ty(),
1195 pred.print_modifiers_and_trait_path()
1196 ));
1197 })
1198 }
1199 code = next_code;
1200 pred = next_pred;
1201 }
1202
1203 diag
1204 }
1205}
1206
1207impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
1208 fn can_match_trait(
1209 &self,
1210 goal: ty::TraitPredicate<'tcx>,
1211 assumption: ty::PolyTraitPredicate<'tcx>,
1212 ) -> bool {
1213 if goal.polarity != assumption.polarity() {
1215 return false;
1216 }
1217
1218 let trait_assumption = self.instantiate_binder_with_fresh_vars(
1219 DUMMY_SP,
1220 infer::BoundRegionConversionTime::HigherRankedType,
1221 assumption,
1222 );
1223
1224 self.can_eq(ty::ParamEnv::empty(), goal.trait_ref, trait_assumption.trait_ref)
1225 }
1226
1227 fn can_match_projection(
1228 &self,
1229 goal: ty::ProjectionPredicate<'tcx>,
1230 assumption: ty::PolyProjectionPredicate<'tcx>,
1231 ) -> bool {
1232 let assumption = self.instantiate_binder_with_fresh_vars(
1233 DUMMY_SP,
1234 infer::BoundRegionConversionTime::HigherRankedType,
1235 assumption,
1236 );
1237
1238 let param_env = ty::ParamEnv::empty();
1239 self.can_eq(param_env, goal.projection_term, assumption.projection_term)
1240 && self.can_eq(param_env, goal.term, assumption.term)
1241 }
1242
1243 #[instrument(level = "debug", skip(self), ret)]
1246 pub(super) fn error_implies(
1247 &self,
1248 cond: ty::Predicate<'tcx>,
1249 error: ty::Predicate<'tcx>,
1250 ) -> bool {
1251 if cond == error {
1252 return true;
1253 }
1254
1255 if let Some(error) = error.as_trait_clause() {
1256 self.enter_forall(error, |error| {
1257 elaborate(self.tcx, std::iter::once(cond))
1258 .filter_map(|implied| implied.as_trait_clause())
1259 .any(|implied| self.can_match_trait(error, implied))
1260 })
1261 } else if let Some(error) = error.as_projection_clause() {
1262 self.enter_forall(error, |error| {
1263 elaborate(self.tcx, std::iter::once(cond))
1264 .filter_map(|implied| implied.as_projection_clause())
1265 .any(|implied| self.can_match_projection(error, implied))
1266 })
1267 } else {
1268 false
1269 }
1270 }
1271
1272 #[instrument(level = "debug", skip_all)]
1273 pub(super) fn report_projection_error(
1274 &self,
1275 obligation: &PredicateObligation<'tcx>,
1276 error: &MismatchedProjectionTypes<'tcx>,
1277 ) -> ErrorGuaranteed {
1278 let predicate = self.resolve_vars_if_possible(obligation.predicate);
1279
1280 if let Err(e) = predicate.error_reported() {
1281 return e;
1282 }
1283
1284 self.probe(|_| {
1285 let bound_predicate = predicate.kind();
1290 let (values, err) = match bound_predicate.skip_binder() {
1291 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
1292 let ocx = ObligationCtxt::new(self);
1293
1294 let data = self.instantiate_binder_with_fresh_vars(
1295 obligation.cause.span,
1296 infer::BoundRegionConversionTime::HigherRankedType,
1297 bound_predicate.rebind(data),
1298 );
1299 let unnormalized_term = data.projection_term.to_term(self.tcx);
1300 let normalized_term =
1303 ocx.normalize(&obligation.cause, obligation.param_env, unnormalized_term);
1304
1305 let _ = ocx.select_where_possible();
1311
1312 if let Err(new_err) =
1313 ocx.eq(&obligation.cause, obligation.param_env, data.term, normalized_term)
1314 {
1315 (
1316 Some((
1317 data.projection_term,
1318 self.resolve_vars_if_possible(normalized_term),
1319 data.term,
1320 )),
1321 new_err,
1322 )
1323 } else {
1324 (None, error.err)
1325 }
1326 }
1327 ty::PredicateKind::AliasRelate(lhs, rhs, _) => {
1328 let derive_better_type_error =
1329 |alias_term: ty::AliasTerm<'tcx>, expected_term: ty::Term<'tcx>| {
1330 let ocx = ObligationCtxt::new(self);
1331
1332 let Ok(normalized_term) = ocx.structurally_normalize_term(
1333 &ObligationCause::dummy(),
1334 obligation.param_env,
1335 alias_term.to_term(self.tcx),
1336 ) else {
1337 return None;
1338 };
1339
1340 if let Err(terr) = ocx.eq(
1341 &ObligationCause::dummy(),
1342 obligation.param_env,
1343 expected_term,
1344 normalized_term,
1345 ) {
1346 Some((terr, self.resolve_vars_if_possible(normalized_term)))
1347 } else {
1348 None
1349 }
1350 };
1351
1352 if let Some(lhs) = lhs.to_alias_term()
1353 && let Some((better_type_err, expected_term)) =
1354 derive_better_type_error(lhs, rhs)
1355 {
1356 (
1357 Some((lhs, self.resolve_vars_if_possible(expected_term), rhs)),
1358 better_type_err,
1359 )
1360 } else if let Some(rhs) = rhs.to_alias_term()
1361 && let Some((better_type_err, expected_term)) =
1362 derive_better_type_error(rhs, lhs)
1363 {
1364 (
1365 Some((rhs, self.resolve_vars_if_possible(expected_term), lhs)),
1366 better_type_err,
1367 )
1368 } else {
1369 (None, error.err)
1370 }
1371 }
1372 _ => (None, error.err),
1373 };
1374
1375 let mut file = None;
1376 let (msg, span, closure_span) = values
1377 .and_then(|(predicate, normalized_term, expected_term)| {
1378 self.maybe_detailed_projection_msg(
1379 obligation.cause.span,
1380 predicate,
1381 normalized_term,
1382 expected_term,
1383 &mut file,
1384 )
1385 })
1386 .unwrap_or_else(|| {
1387 (
1388 with_forced_trimmed_paths!(format!(
1389 "type mismatch resolving `{}`",
1390 self.tcx
1391 .short_string(self.resolve_vars_if_possible(predicate), &mut file),
1392 )),
1393 obligation.cause.span,
1394 None,
1395 )
1396 });
1397 let mut diag = struct_span_code_err!(self.dcx(), span, E0271, "{msg}");
1398 *diag.long_ty_path() = file;
1399 if let Some(span) = closure_span {
1400 diag.span_label(span, "this closure");
1417 if !span.overlaps(obligation.cause.span) {
1418 diag.span_label(obligation.cause.span, "closure used here");
1420 }
1421 }
1422
1423 let secondary_span = (|| {
1424 let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1425 predicate.kind().skip_binder()
1426 else {
1427 return None;
1428 };
1429
1430 let trait_assoc_item = self.tcx.opt_associated_item(proj.projection_term.def_id)?;
1431 let trait_assoc_ident = trait_assoc_item.ident(self.tcx);
1432
1433 let mut associated_items = vec![];
1434 self.tcx.for_each_relevant_impl(
1435 self.tcx.trait_of_item(proj.projection_term.def_id)?,
1436 proj.projection_term.self_ty(),
1437 |impl_def_id| {
1438 associated_items.extend(
1439 self.tcx
1440 .associated_items(impl_def_id)
1441 .in_definition_order()
1442 .find(|assoc| assoc.ident(self.tcx) == trait_assoc_ident),
1443 );
1444 },
1445 );
1446
1447 let [associated_item]: &[ty::AssocItem] = &associated_items[..] else {
1448 return None;
1449 };
1450 match self.tcx.hir().get_if_local(associated_item.def_id) {
1451 Some(
1452 hir::Node::TraitItem(hir::TraitItem {
1453 kind: hir::TraitItemKind::Type(_, Some(ty)),
1454 ..
1455 })
1456 | hir::Node::ImplItem(hir::ImplItem {
1457 kind: hir::ImplItemKind::Type(ty),
1458 ..
1459 }),
1460 ) => Some((
1461 ty.span,
1462 with_forced_trimmed_paths!(Cow::from(format!(
1463 "type mismatch resolving `{}`",
1464 self.tcx.short_string(
1465 self.resolve_vars_if_possible(predicate),
1466 diag.long_ty_path()
1467 ),
1468 ))),
1469 true,
1470 )),
1471 _ => None,
1472 }
1473 })();
1474
1475 self.note_type_err(
1476 &mut diag,
1477 &obligation.cause,
1478 secondary_span,
1479 values.map(|(_, normalized_ty, expected_ty)| {
1480 obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(
1481 expected_ty,
1482 normalized_ty,
1483 )))
1484 }),
1485 err,
1486 false,
1487 Some(span),
1488 );
1489 self.note_obligation_cause(&mut diag, obligation);
1490 diag.emit()
1491 })
1492 }
1493
1494 fn maybe_detailed_projection_msg(
1495 &self,
1496 mut span: Span,
1497 projection_term: ty::AliasTerm<'tcx>,
1498 normalized_ty: ty::Term<'tcx>,
1499 expected_ty: ty::Term<'tcx>,
1500 file: &mut Option<PathBuf>,
1501 ) -> Option<(String, Span, Option<Span>)> {
1502 let trait_def_id = projection_term.trait_def_id(self.tcx);
1503 let self_ty = projection_term.self_ty();
1504
1505 with_forced_trimmed_paths! {
1506 if self.tcx.is_lang_item(projection_term.def_id, LangItem::FnOnceOutput) {
1507 let (span, closure_span) = if let ty::Closure(def_id, _) = self_ty.kind() {
1508 let def_span = self.tcx.def_span(def_id);
1509 if let Some(local_def_id) = def_id.as_local()
1510 && let node = self.tcx.hir_node_by_def_id(local_def_id)
1511 && let Some(fn_decl) = node.fn_decl()
1512 && let Some(id) = node.body_id()
1513 {
1514 span = match fn_decl.output {
1515 hir::FnRetTy::Return(ty) => ty.span,
1516 hir::FnRetTy::DefaultReturn(_) => {
1517 let body = self.tcx.hir().body(id);
1518 match body.value.kind {
1519 hir::ExprKind::Block(
1520 hir::Block { expr: Some(expr), .. },
1521 _,
1522 ) => expr.span,
1523 hir::ExprKind::Block(
1524 hir::Block {
1525 expr: None, stmts: [.., last], ..
1526 },
1527 _,
1528 ) => last.span,
1529 _ => body.value.span,
1530 }
1531 }
1532 };
1533 }
1534 (span, Some(def_span))
1535 } else {
1536 (span, None)
1537 };
1538 let item = match self_ty.kind() {
1539 ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
1540 _ => self.tcx.short_string(self_ty, file),
1541 };
1542 Some((format!(
1543 "expected `{item}` to return `{expected_ty}`, but it returns `{normalized_ty}`",
1544 ), span, closure_span))
1545 } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
1546 Some((format!(
1547 "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
1548 resolves to `{normalized_ty}`"
1549 ), span, None))
1550 } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
1551 Some((format!(
1552 "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
1553 yields `{normalized_ty}`"
1554 ), span, None))
1555 } else {
1556 None
1557 }
1558 }
1559 }
1560
1561 pub fn fuzzy_match_tys(
1562 &self,
1563 mut a: Ty<'tcx>,
1564 mut b: Ty<'tcx>,
1565 ignoring_lifetimes: bool,
1566 ) -> Option<CandidateSimilarity> {
1567 fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
1570 match t.kind() {
1571 ty::Bool => Some(0),
1572 ty::Char => Some(1),
1573 ty::Str => Some(2),
1574 ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => Some(2),
1575 ty::Int(..)
1576 | ty::Uint(..)
1577 | ty::Float(..)
1578 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
1579 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1580 ty::Array(..) | ty::Slice(..) => Some(6),
1581 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1582 ty::Dynamic(..) => Some(8),
1583 ty::Closure(..) => Some(9),
1584 ty::Tuple(..) => Some(10),
1585 ty::Param(..) => Some(11),
1586 ty::Alias(ty::Projection, ..) => Some(12),
1587 ty::Alias(ty::Inherent, ..) => Some(13),
1588 ty::Alias(ty::Opaque, ..) => Some(14),
1589 ty::Alias(ty::Weak, ..) => Some(15),
1590 ty::Never => Some(16),
1591 ty::Adt(..) => Some(17),
1592 ty::Coroutine(..) => Some(18),
1593 ty::Foreign(..) => Some(19),
1594 ty::CoroutineWitness(..) => Some(20),
1595 ty::CoroutineClosure(..) => Some(21),
1596 ty::Pat(..) => Some(22),
1597 ty::UnsafeBinder(..) => Some(23),
1598 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1599 }
1600 }
1601
1602 let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
1603 loop {
1604 match t.kind() {
1605 ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => t = *inner,
1606 _ => break t,
1607 }
1608 }
1609 };
1610
1611 if !ignoring_lifetimes {
1612 a = strip_references(a);
1613 b = strip_references(b);
1614 }
1615
1616 let cat_a = type_category(self.tcx, a)?;
1617 let cat_b = type_category(self.tcx, b)?;
1618 if a == b {
1619 Some(CandidateSimilarity::Exact { ignoring_lifetimes })
1620 } else if cat_a == cat_b {
1621 match (a.kind(), b.kind()) {
1622 (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
1623 (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
1624 (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
1630 self.fuzzy_match_tys(a, b, true).is_some()
1631 }
1632 _ => true,
1633 }
1634 .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
1635 } else if ignoring_lifetimes {
1636 None
1637 } else {
1638 self.fuzzy_match_tys(a, b, true)
1639 }
1640 }
1641
1642 pub(super) fn describe_closure(&self, kind: hir::ClosureKind) -> &'static str {
1643 match kind {
1644 hir::ClosureKind::Closure => "a closure",
1645 hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => "a coroutine",
1646 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1647 hir::CoroutineDesugaring::Async,
1648 hir::CoroutineSource::Block,
1649 )) => "an async block",
1650 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1651 hir::CoroutineDesugaring::Async,
1652 hir::CoroutineSource::Fn,
1653 )) => "an async function",
1654 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1655 hir::CoroutineDesugaring::Async,
1656 hir::CoroutineSource::Closure,
1657 ))
1658 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
1659 "an async closure"
1660 }
1661 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1662 hir::CoroutineDesugaring::AsyncGen,
1663 hir::CoroutineSource::Block,
1664 )) => "an async gen block",
1665 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1666 hir::CoroutineDesugaring::AsyncGen,
1667 hir::CoroutineSource::Fn,
1668 )) => "an async gen function",
1669 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1670 hir::CoroutineDesugaring::AsyncGen,
1671 hir::CoroutineSource::Closure,
1672 ))
1673 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
1674 "an async gen closure"
1675 }
1676 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1677 hir::CoroutineDesugaring::Gen,
1678 hir::CoroutineSource::Block,
1679 )) => "a gen block",
1680 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1681 hir::CoroutineDesugaring::Gen,
1682 hir::CoroutineSource::Fn,
1683 )) => "a gen function",
1684 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1685 hir::CoroutineDesugaring::Gen,
1686 hir::CoroutineSource::Closure,
1687 ))
1688 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => "a gen closure",
1689 }
1690 }
1691
1692 pub(super) fn find_similar_impl_candidates(
1693 &self,
1694 trait_pred: ty::PolyTraitPredicate<'tcx>,
1695 ) -> Vec<ImplCandidate<'tcx>> {
1696 let mut candidates: Vec<_> = self
1697 .tcx
1698 .all_impls(trait_pred.def_id())
1699 .filter_map(|def_id| {
1700 let imp = self.tcx.impl_trait_header(def_id).unwrap();
1701 if imp.polarity != ty::ImplPolarity::Positive
1702 || !self.tcx.is_user_visible_dep(def_id.krate)
1703 {
1704 return None;
1705 }
1706 let imp = imp.trait_ref.skip_binder();
1707
1708 self.fuzzy_match_tys(trait_pred.skip_binder().self_ty(), imp.self_ty(), false).map(
1709 |similarity| ImplCandidate { trait_ref: imp, similarity, impl_def_id: def_id },
1710 )
1711 })
1712 .collect();
1713 if candidates.iter().any(|c| matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
1714 candidates.retain(|c| matches!(c.similarity, CandidateSimilarity::Exact { .. }));
1718 }
1719 candidates
1720 }
1721
1722 pub(super) fn report_similar_impl_candidates(
1723 &self,
1724 impl_candidates: &[ImplCandidate<'tcx>],
1725 trait_pred: ty::PolyTraitPredicate<'tcx>,
1726 body_def_id: LocalDefId,
1727 err: &mut Diag<'_>,
1728 other: bool,
1729 param_env: ty::ParamEnv<'tcx>,
1730 ) -> bool {
1731 let alternative_candidates = |def_id: DefId| {
1732 let mut impl_candidates: Vec<_> = self
1733 .tcx
1734 .all_impls(def_id)
1735 .filter(|def_id| !self.tcx.do_not_recommend_impl(*def_id))
1737 .filter_map(|def_id| self.tcx.impl_trait_header(def_id))
1739 .filter_map(|header| {
1740 (header.polarity != ty::ImplPolarity::Negative
1741 || self.tcx.is_automatically_derived(def_id))
1742 .then(|| header.trait_ref.instantiate_identity())
1743 })
1744 .filter(|trait_ref| {
1745 let self_ty = trait_ref.self_ty();
1746 if let ty::Param(_) = self_ty.kind() {
1748 false
1749 }
1750 else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
1752 self.tcx.visibility(def.did()).is_accessible_from(body_def_id, self.tcx)
1756 } else {
1757 true
1758 }
1759 })
1760 .collect();
1761
1762 impl_candidates.sort_by_key(|tr| tr.to_string());
1763 impl_candidates.dedup();
1764 impl_candidates
1765 };
1766
1767 let trait_def_id = trait_pred.def_id();
1771 let trait_name = self.tcx.item_name(trait_def_id);
1772 let crate_name = self.tcx.crate_name(trait_def_id.krate);
1773 if let Some(other_trait_def_id) = self.tcx.all_traits().find(|def_id| {
1774 trait_name == self.tcx.item_name(trait_def_id)
1775 && trait_def_id.krate != def_id.krate
1776 && crate_name == self.tcx.crate_name(def_id.krate)
1777 }) {
1778 let found_type =
1782 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind() {
1783 Some(def.did())
1784 } else {
1785 None
1786 };
1787 let candidates = if impl_candidates.is_empty() {
1788 alternative_candidates(trait_def_id)
1789 } else {
1790 impl_candidates.into_iter().map(|cand| cand.trait_ref).collect()
1791 };
1792 let mut span: MultiSpan = self.tcx.def_span(trait_def_id).into();
1793 span.push_span_label(self.tcx.def_span(trait_def_id), "this is the required trait");
1794 for (sp, label) in [trait_def_id, other_trait_def_id]
1795 .iter()
1796 .filter(|def_id| !def_id.is_local())
1800 .filter_map(|def_id| self.tcx.extern_crate(def_id.krate))
1801 .map(|data| {
1802 let dependency = if data.dependency_of == LOCAL_CRATE {
1803 "direct dependency of the current crate".to_string()
1804 } else {
1805 let dep = self.tcx.crate_name(data.dependency_of);
1806 format!("dependency of crate `{dep}`")
1807 };
1808 (
1809 data.span,
1810 format!("one version of crate `{crate_name}` used here, as a {dependency}"),
1811 )
1812 })
1813 {
1814 span.push_span_label(sp, label);
1815 }
1816 let mut points_at_type = false;
1817 if let Some(found_type) = found_type {
1818 span.push_span_label(
1819 self.tcx.def_span(found_type),
1820 "this type doesn't implement the required trait",
1821 );
1822 for trait_ref in candidates {
1823 if let ty::Adt(def, _) = trait_ref.self_ty().peel_refs().kind()
1824 && let candidate_def_id = def.did()
1825 && let Some(name) = self.tcx.opt_item_name(candidate_def_id)
1826 && let Some(found) = self.tcx.opt_item_name(found_type)
1827 && name == found
1828 && candidate_def_id.krate != found_type.krate
1829 && self.tcx.crate_name(candidate_def_id.krate)
1830 == self.tcx.crate_name(found_type.krate)
1831 {
1832 let candidate_span = self.tcx.def_span(candidate_def_id);
1835 span.push_span_label(
1836 candidate_span,
1837 "this type implements the required trait",
1838 );
1839 points_at_type = true;
1840 }
1841 }
1842 }
1843 span.push_span_label(self.tcx.def_span(other_trait_def_id), "this is the found trait");
1844 err.highlighted_span_note(
1845 span,
1846 vec![
1847 StringPart::normal("there are ".to_string()),
1848 StringPart::highlighted("multiple different versions".to_string()),
1849 StringPart::normal(" of crate `".to_string()),
1850 StringPart::highlighted(format!("{crate_name}")),
1851 StringPart::normal("` in the dependency graph\n".to_string()),
1852 ],
1853 );
1854 if points_at_type {
1855 err.highlighted_note(vec![
1860 StringPart::normal(
1861 "two types coming from two different versions of the same crate are \
1862 different types "
1863 .to_string(),
1864 ),
1865 StringPart::highlighted("even if they look the same".to_string()),
1866 ]);
1867 }
1868 err.highlighted_help(vec![
1869 StringPart::normal("you can use `".to_string()),
1870 StringPart::highlighted("cargo tree".to_string()),
1871 StringPart::normal("` to explore your dependency tree".to_string()),
1872 ]);
1873 return true;
1874 }
1875
1876 if let [single] = &impl_candidates {
1877 if self.probe(|_| {
1880 let ocx = ObligationCtxt::new(self);
1881
1882 self.enter_forall(trait_pred, |obligation_trait_ref| {
1883 let impl_args = self.fresh_args_for_item(DUMMY_SP, single.impl_def_id);
1884 let impl_trait_ref = ocx.normalize(
1885 &ObligationCause::dummy(),
1886 param_env,
1887 ty::EarlyBinder::bind(single.trait_ref).instantiate(self.tcx, impl_args),
1888 );
1889
1890 ocx.register_obligations(
1891 self.tcx
1892 .predicates_of(single.impl_def_id)
1893 .instantiate(self.tcx, impl_args)
1894 .into_iter()
1895 .map(|(clause, _)| {
1896 Obligation::new(
1897 self.tcx,
1898 ObligationCause::dummy(),
1899 param_env,
1900 clause,
1901 )
1902 }),
1903 );
1904 if !ocx.select_where_possible().is_empty() {
1905 return false;
1906 }
1907
1908 let mut terrs = vec![];
1909 for (obligation_arg, impl_arg) in
1910 std::iter::zip(obligation_trait_ref.trait_ref.args, impl_trait_ref.args)
1911 {
1912 if (obligation_arg, impl_arg).references_error() {
1913 return false;
1914 }
1915 if let Err(terr) =
1916 ocx.eq(&ObligationCause::dummy(), param_env, impl_arg, obligation_arg)
1917 {
1918 terrs.push(terr);
1919 }
1920 if !ocx.select_where_possible().is_empty() {
1921 return false;
1922 }
1923 }
1924
1925 if terrs.len() == impl_trait_ref.args.len() {
1927 return false;
1928 }
1929
1930 let impl_trait_ref = self.resolve_vars_if_possible(impl_trait_ref);
1931 if impl_trait_ref.references_error() {
1932 return false;
1933 }
1934
1935 if let [child, ..] = &err.children[..]
1936 && child.level == Level::Help
1937 && let Some(line) = child.messages.get(0)
1938 && let Some(line) = line.0.as_str()
1939 && line.starts_with("the trait")
1940 && line.contains("is not implemented for")
1941 {
1942 err.children.remove(0);
1949 }
1950
1951 let traits = self.cmp_traits(
1952 obligation_trait_ref.def_id(),
1953 &obligation_trait_ref.trait_ref.args[1..],
1954 impl_trait_ref.def_id,
1955 &impl_trait_ref.args[1..],
1956 );
1957 let traits_content = (traits.0.content(), traits.1.content());
1958 let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty());
1959 let types_content = (types.0.content(), types.1.content());
1960 let mut msg = vec![StringPart::normal("the trait `")];
1961 if traits_content.0 == traits_content.1 {
1962 msg.push(StringPart::normal(
1963 impl_trait_ref.print_trait_sugared().to_string(),
1964 ));
1965 } else {
1966 msg.extend(traits.0.0);
1967 }
1968 msg.extend([
1969 StringPart::normal("` "),
1970 StringPart::highlighted("is not"),
1971 StringPart::normal(" implemented for `"),
1972 ]);
1973 if types_content.0 == types_content.1 {
1974 let ty = self
1975 .tcx
1976 .short_string(obligation_trait_ref.self_ty(), err.long_ty_path());
1977 msg.push(StringPart::normal(ty));
1978 } else {
1979 msg.extend(types.0.0);
1980 }
1981 msg.push(StringPart::normal("`"));
1982 if types_content.0 == types_content.1 {
1983 msg.push(StringPart::normal("\nbut trait `"));
1984 msg.extend(traits.1.0);
1985 msg.extend([
1986 StringPart::normal("` "),
1987 StringPart::highlighted("is"),
1988 StringPart::normal(" implemented for it"),
1989 ]);
1990 } else if traits_content.0 == traits_content.1 {
1991 msg.extend([
1992 StringPart::normal("\nbut it "),
1993 StringPart::highlighted("is"),
1994 StringPart::normal(" implemented for `"),
1995 ]);
1996 msg.extend(types.1.0);
1997 msg.push(StringPart::normal("`"));
1998 } else {
1999 msg.push(StringPart::normal("\nbut trait `"));
2000 msg.extend(traits.1.0);
2001 msg.extend([
2002 StringPart::normal("` "),
2003 StringPart::highlighted("is"),
2004 StringPart::normal(" implemented for `"),
2005 ]);
2006 msg.extend(types.1.0);
2007 msg.push(StringPart::normal("`"));
2008 }
2009 err.highlighted_help(msg);
2010
2011 if let [TypeError::Sorts(exp_found)] = &terrs[..] {
2012 let exp_found = self.resolve_vars_if_possible(*exp_found);
2013 err.highlighted_help(vec![
2014 StringPart::normal("for that trait implementation, "),
2015 StringPart::normal("expected `"),
2016 StringPart::highlighted(exp_found.expected.to_string()),
2017 StringPart::normal("`, found `"),
2018 StringPart::highlighted(exp_found.found.to_string()),
2019 StringPart::normal("`"),
2020 ]);
2021 self.suggest_function_pointers_impl(None, &exp_found, err);
2022 }
2023
2024 true
2025 })
2026 }) {
2027 return true;
2028 }
2029 }
2030
2031 let other = if other { "other " } else { "" };
2032 let report = |mut candidates: Vec<TraitRef<'tcx>>, err: &mut Diag<'_>| {
2033 candidates.retain(|tr| !tr.references_error());
2034 if candidates.is_empty() {
2035 return false;
2036 }
2037 if let &[cand] = &candidates[..] {
2038 let (desc, mention_castable) =
2039 match (cand.self_ty().kind(), trait_pred.self_ty().skip_binder().kind()) {
2040 (ty::FnPtr(..), ty::FnDef(..)) => {
2041 (" implemented for fn pointer `", ", cast using `as`")
2042 }
2043 (ty::FnPtr(..), _) => (" implemented for fn pointer `", ""),
2044 _ => (" implemented for `", ""),
2045 };
2046 err.highlighted_help(vec![
2047 StringPart::normal(format!("the trait `{}` ", cand.print_trait_sugared())),
2048 StringPart::highlighted("is"),
2049 StringPart::normal(desc),
2050 StringPart::highlighted(cand.self_ty().to_string()),
2051 StringPart::normal("`"),
2052 StringPart::normal(mention_castable),
2053 ]);
2054 return true;
2055 }
2056 let trait_ref = TraitRef::identity(self.tcx, candidates[0].def_id);
2057 let mut traits: Vec<_> =
2059 candidates.iter().map(|c| c.print_only_trait_path().to_string()).collect();
2060 traits.sort();
2061 traits.dedup();
2062 let all_traits_equal = traits.len() == 1;
2065
2066 let candidates: Vec<String> = candidates
2067 .into_iter()
2068 .map(|c| {
2069 if all_traits_equal {
2070 format!("\n {}", c.self_ty())
2071 } else {
2072 format!("\n `{}` implements `{}`", c.self_ty(), c.print_only_trait_path())
2073 }
2074 })
2075 .collect();
2076
2077 let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose {
2078 candidates.len()
2079 } else {
2080 8
2081 };
2082 err.help(format!(
2083 "the following {other}types implement trait `{}`:{}{}",
2084 trait_ref.print_trait_sugared(),
2085 candidates[..end].join(""),
2086 if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
2087 format!("\nand {} others", candidates.len() - 8)
2088 } else {
2089 String::new()
2090 }
2091 ));
2092 true
2093 };
2094
2095 let impl_candidates = impl_candidates
2098 .into_iter()
2099 .cloned()
2100 .filter(|cand| !self.tcx.do_not_recommend_impl(cand.impl_def_id))
2101 .collect::<Vec<_>>();
2102
2103 let def_id = trait_pred.def_id();
2104 if impl_candidates.is_empty() {
2105 if self.tcx.trait_is_auto(def_id)
2106 || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2107 || self.tcx.get_diagnostic_name(def_id).is_some()
2108 {
2109 return false;
2111 }
2112 return report(alternative_candidates(def_id), err);
2113 }
2114
2115 let mut impl_candidates: Vec<_> = impl_candidates
2122 .iter()
2123 .cloned()
2124 .filter(|cand| !cand.trait_ref.references_error())
2125 .map(|mut cand| {
2126 cand.trait_ref = self
2130 .tcx
2131 .try_normalize_erasing_regions(
2132 ty::TypingEnv::non_body_analysis(self.tcx, cand.impl_def_id),
2133 cand.trait_ref,
2134 )
2135 .unwrap_or(cand.trait_ref);
2136 cand
2137 })
2138 .collect();
2139 impl_candidates.sort_by_key(|cand| (cand.similarity, cand.trait_ref.to_string()));
2140 let mut impl_candidates: Vec<_> =
2141 impl_candidates.into_iter().map(|cand| cand.trait_ref).collect();
2142 impl_candidates.dedup();
2143
2144 report(impl_candidates, err)
2145 }
2146
2147 fn report_similar_impl_candidates_for_root_obligation(
2148 &self,
2149 obligation: &PredicateObligation<'tcx>,
2150 trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2151 body_def_id: LocalDefId,
2152 err: &mut Diag<'_>,
2153 ) {
2154 let mut code = obligation.cause.code();
2161 let mut trait_pred = trait_predicate;
2162 let mut peeled = false;
2163 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
2164 code = parent_code;
2165 if let Some(parent_trait_pred) = parent_trait_pred {
2166 trait_pred = parent_trait_pred;
2167 peeled = true;
2168 }
2169 }
2170 let def_id = trait_pred.def_id();
2171 if peeled
2177 && !self.tcx.trait_is_auto(def_id)
2178 && !self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2179 {
2180 let impl_candidates = self.find_similar_impl_candidates(trait_pred);
2181 self.report_similar_impl_candidates(
2182 &impl_candidates,
2183 trait_pred,
2184 body_def_id,
2185 err,
2186 true,
2187 obligation.param_env,
2188 );
2189 }
2190 }
2191
2192 fn get_parent_trait_ref(
2194 &self,
2195 code: &ObligationCauseCode<'tcx>,
2196 ) -> Option<(Ty<'tcx>, Option<Span>)> {
2197 match code {
2198 ObligationCauseCode::BuiltinDerived(data) => {
2199 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2200 match self.get_parent_trait_ref(&data.parent_code) {
2201 Some(t) => Some(t),
2202 None => {
2203 let ty = parent_trait_ref.skip_binder().self_ty();
2204 let span = TyCategory::from_ty(self.tcx, ty)
2205 .map(|(_, def_id)| self.tcx.def_span(def_id));
2206 Some((ty, span))
2207 }
2208 }
2209 }
2210 ObligationCauseCode::FunctionArg { parent_code, .. } => {
2211 self.get_parent_trait_ref(parent_code)
2212 }
2213 _ => None,
2214 }
2215 }
2216
2217 fn note_version_mismatch(
2221 &self,
2222 err: &mut Diag<'_>,
2223 trait_pred: ty::PolyTraitPredicate<'tcx>,
2224 ) -> bool {
2225 let get_trait_impls = |trait_def_id| {
2226 let mut trait_impls = vec![];
2227 self.tcx.for_each_relevant_impl(
2228 trait_def_id,
2229 trait_pred.skip_binder().self_ty(),
2230 |impl_def_id| {
2231 trait_impls.push(impl_def_id);
2232 },
2233 );
2234 trait_impls
2235 };
2236
2237 let required_trait_path = self.tcx.def_path_str(trait_pred.def_id());
2238 let traits_with_same_path: UnordSet<_> = self
2239 .tcx
2240 .visible_traits()
2241 .filter(|trait_def_id| *trait_def_id != trait_pred.def_id())
2242 .map(|trait_def_id| (self.tcx.def_path_str(trait_def_id), trait_def_id))
2243 .filter(|(p, _)| *p == required_trait_path)
2244 .collect();
2245
2246 let traits_with_same_path =
2247 traits_with_same_path.into_items().into_sorted_stable_ord_by_key(|(p, _)| p);
2248 let mut suggested = false;
2249 for (_, trait_with_same_path) in traits_with_same_path {
2250 let trait_impls = get_trait_impls(trait_with_same_path);
2251 if trait_impls.is_empty() {
2252 continue;
2253 }
2254 let impl_spans: Vec<_> =
2255 trait_impls.iter().map(|impl_def_id| self.tcx.def_span(*impl_def_id)).collect();
2256 err.span_help(
2257 impl_spans,
2258 format!("trait impl{} with same name found", pluralize!(trait_impls.len())),
2259 );
2260 let trait_crate = self.tcx.crate_name(trait_with_same_path.krate);
2261 let crate_msg =
2262 format!("perhaps two different versions of crate `{trait_crate}` are being used?");
2263 err.note(crate_msg);
2264 suggested = true;
2265 }
2266 suggested
2267 }
2268
2269 pub(super) fn mk_trait_obligation_with_new_self_ty(
2274 &self,
2275 param_env: ty::ParamEnv<'tcx>,
2276 trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
2277 ) -> PredicateObligation<'tcx> {
2278 let trait_pred =
2279 trait_ref_and_ty.map_bound(|(tr, new_self_ty)| tr.with_self_ty(self.tcx, new_self_ty));
2280
2281 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
2282 }
2283
2284 fn predicate_can_apply(
2287 &self,
2288 param_env: ty::ParamEnv<'tcx>,
2289 pred: ty::PolyTraitPredicate<'tcx>,
2290 ) -> bool {
2291 struct ParamToVarFolder<'a, 'tcx> {
2292 infcx: &'a InferCtxt<'tcx>,
2293 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2294 }
2295
2296 impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
2297 fn cx(&self) -> TyCtxt<'tcx> {
2298 self.infcx.tcx
2299 }
2300
2301 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2302 if let ty::Param(_) = *ty.kind() {
2303 let infcx = self.infcx;
2304 *self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
2305 } else {
2306 ty.super_fold_with(self)
2307 }
2308 }
2309 }
2310
2311 self.probe(|_| {
2312 let cleaned_pred =
2313 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2314
2315 let InferOk { value: cleaned_pred, .. } =
2316 self.infcx.at(&ObligationCause::dummy(), param_env).normalize(cleaned_pred);
2317
2318 let obligation =
2319 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
2320
2321 self.predicate_may_hold(&obligation)
2322 })
2323 }
2324
2325 pub fn note_obligation_cause(
2326 &self,
2327 err: &mut Diag<'_>,
2328 obligation: &PredicateObligation<'tcx>,
2329 ) {
2330 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2333 self.note_obligation_cause_code(
2334 obligation.cause.body_id,
2335 err,
2336 obligation.predicate,
2337 obligation.param_env,
2338 obligation.cause.code(),
2339 &mut vec![],
2340 &mut Default::default(),
2341 );
2342 self.suggest_unsized_bound_if_applicable(err, obligation);
2343 if let Some(span) = err.span.primary_span()
2344 && let Some(mut diag) =
2345 self.dcx().steal_non_err(span, StashKey::AssociatedTypeSuggestion)
2346 && let Suggestions::Enabled(ref mut s1) = err.suggestions
2347 && let Suggestions::Enabled(ref mut s2) = diag.suggestions
2348 {
2349 s1.append(s2);
2350 diag.cancel()
2351 }
2352 }
2353 }
2354
2355 pub(super) fn is_recursive_obligation(
2356 &self,
2357 obligated_types: &mut Vec<Ty<'tcx>>,
2358 cause_code: &ObligationCauseCode<'tcx>,
2359 ) -> bool {
2360 if let ObligationCauseCode::BuiltinDerived(ref data) = cause_code {
2361 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2362 let self_ty = parent_trait_ref.skip_binder().self_ty();
2363 if obligated_types.iter().any(|ot| ot == &self_ty) {
2364 return true;
2365 }
2366 if let ty::Adt(def, args) = self_ty.kind()
2367 && let [arg] = &args[..]
2368 && let ty::GenericArgKind::Type(ty) = arg.unpack()
2369 && let ty::Adt(inner_def, _) = ty.kind()
2370 && inner_def == def
2371 {
2372 return true;
2373 }
2374 }
2375 false
2376 }
2377
2378 fn get_standard_error_message(
2379 &self,
2380 trait_predicate: ty::PolyTraitPredicate<'tcx>,
2381 message: Option<String>,
2382 predicate_constness: Option<ty::BoundConstness>,
2383 append_const_msg: Option<AppendConstMessage>,
2384 post_message: String,
2385 long_ty_file: &mut Option<PathBuf>,
2386 ) -> String {
2387 message
2388 .and_then(|cannot_do_this| {
2389 match (predicate_constness, append_const_msg) {
2390 (None, _) => Some(cannot_do_this),
2392 (
2394 Some(ty::BoundConstness::Const | ty::BoundConstness::Maybe),
2395 Some(AppendConstMessage::Default),
2396 ) => Some(format!("{cannot_do_this} in const contexts")),
2397 (
2399 Some(ty::BoundConstness::Const | ty::BoundConstness::Maybe),
2400 Some(AppendConstMessage::Custom(custom_msg, _)),
2401 ) => Some(format!("{cannot_do_this}{custom_msg}")),
2402 (Some(ty::BoundConstness::Const | ty::BoundConstness::Maybe), None) => None,
2404 }
2405 })
2406 .unwrap_or_else(|| {
2407 format!(
2408 "the trait bound `{}` is not satisfied{post_message}",
2409 self.tcx.short_string(
2410 trait_predicate.print_with_bound_constness(predicate_constness),
2411 long_ty_file,
2412 ),
2413 )
2414 })
2415 }
2416
2417 fn get_safe_transmute_error_and_reason(
2418 &self,
2419 obligation: PredicateObligation<'tcx>,
2420 trait_pred: ty::PolyTraitPredicate<'tcx>,
2421 span: Span,
2422 ) -> GetSafeTransmuteErrorAndReason {
2423 use rustc_transmute::Answer;
2424 self.probe(|_| {
2425 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
2428 return GetSafeTransmuteErrorAndReason::Default;
2429 }
2430
2431 let trait_pred =
2433 self.tcx.erase_regions(self.tcx.instantiate_bound_regions_with_erased(trait_pred));
2434
2435 let src_and_dst = rustc_transmute::Types {
2436 dst: trait_pred.trait_ref.args.type_at(0),
2437 src: trait_pred.trait_ref.args.type_at(1),
2438 };
2439
2440 let ocx = ObligationCtxt::new(self);
2441 let Ok(assume) = ocx.structurally_normalize_const(
2442 &obligation.cause,
2443 obligation.param_env,
2444 trait_pred.trait_ref.args.const_at(2),
2445 ) else {
2446 self.dcx().span_delayed_bug(
2447 span,
2448 "Unable to construct rustc_transmute::Assume where it was previously possible",
2449 );
2450 return GetSafeTransmuteErrorAndReason::Silent;
2451 };
2452
2453 let Some(assume) =
2454 rustc_transmute::Assume::from_const(self.infcx.tcx, obligation.param_env, assume)
2455 else {
2456 self.dcx().span_delayed_bug(
2457 span,
2458 "Unable to construct rustc_transmute::Assume where it was previously possible",
2459 );
2460 return GetSafeTransmuteErrorAndReason::Silent;
2461 };
2462
2463 let dst = trait_pred.trait_ref.args.type_at(0);
2464 let src = trait_pred.trait_ref.args.type_at(1);
2465 let err_msg = format!("`{src}` cannot be safely transmuted into `{dst}`");
2466
2467 match rustc_transmute::TransmuteTypeEnv::new(self.infcx).is_transmutable(
2468 obligation.cause,
2469 src_and_dst,
2470 assume,
2471 ) {
2472 Answer::No(reason) => {
2473 let safe_transmute_explanation = match reason {
2474 rustc_transmute::Reason::SrcIsNotYetSupported => {
2475 format!("analyzing the transmutability of `{src}` is not yet supported")
2476 }
2477
2478 rustc_transmute::Reason::DstIsNotYetSupported => {
2479 format!("analyzing the transmutability of `{dst}` is not yet supported")
2480 }
2481
2482 rustc_transmute::Reason::DstIsBitIncompatible => {
2483 format!(
2484 "at least one value of `{src}` isn't a bit-valid value of `{dst}`"
2485 )
2486 }
2487
2488 rustc_transmute::Reason::DstUninhabited => {
2489 format!("`{dst}` is uninhabited")
2490 }
2491
2492 rustc_transmute::Reason::DstMayHaveSafetyInvariants => {
2493 format!("`{dst}` may carry safety invariants")
2494 }
2495 rustc_transmute::Reason::DstIsTooBig => {
2496 format!("the size of `{src}` is smaller than the size of `{dst}`")
2497 }
2498 rustc_transmute::Reason::DstRefIsTooBig { src, dst } => {
2499 let src_size = src.size;
2500 let dst_size = dst.size;
2501 format!(
2502 "the referent size of `{src}` ({src_size} bytes) \
2503 is smaller than that of `{dst}` ({dst_size} bytes)"
2504 )
2505 }
2506 rustc_transmute::Reason::SrcSizeOverflow => {
2507 format!(
2508 "values of the type `{src}` are too big for the target architecture"
2509 )
2510 }
2511 rustc_transmute::Reason::DstSizeOverflow => {
2512 format!(
2513 "values of the type `{dst}` are too big for the target architecture"
2514 )
2515 }
2516 rustc_transmute::Reason::DstHasStricterAlignment {
2517 src_min_align,
2518 dst_min_align,
2519 } => {
2520 format!(
2521 "the minimum alignment of `{src}` ({src_min_align}) should \
2522 be greater than that of `{dst}` ({dst_min_align})"
2523 )
2524 }
2525 rustc_transmute::Reason::DstIsMoreUnique => {
2526 format!(
2527 "`{src}` is a shared reference, but `{dst}` is a unique reference"
2528 )
2529 }
2530 rustc_transmute::Reason::TypeError => {
2532 return GetSafeTransmuteErrorAndReason::Silent;
2533 }
2534 rustc_transmute::Reason::SrcLayoutUnknown => {
2535 format!("`{src}` has an unknown layout")
2536 }
2537 rustc_transmute::Reason::DstLayoutUnknown => {
2538 format!("`{dst}` has an unknown layout")
2539 }
2540 };
2541 GetSafeTransmuteErrorAndReason::Error {
2542 err_msg,
2543 safe_transmute_explanation: Some(safe_transmute_explanation),
2544 }
2545 }
2546 Answer::Yes => span_bug!(
2548 span,
2549 "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
2550 ),
2551 Answer::If(_) => GetSafeTransmuteErrorAndReason::Error {
2556 err_msg,
2557 safe_transmute_explanation: None,
2558 },
2559 }
2560 })
2561 }
2562
2563 fn add_tuple_trait_message(
2564 &self,
2565 obligation_cause_code: &ObligationCauseCode<'tcx>,
2566 err: &mut Diag<'_>,
2567 ) {
2568 match obligation_cause_code {
2569 ObligationCauseCode::RustCall => {
2570 err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
2571 }
2572 ObligationCauseCode::WhereClause(def_id, _) if self.tcx.is_fn_trait(*def_id) => {
2573 err.code(E0059);
2574 err.primary_message(format!(
2575 "type parameter to bare `{}` trait must be a tuple",
2576 self.tcx.def_path_str(*def_id)
2577 ));
2578 }
2579 _ => {}
2580 }
2581 }
2582
2583 fn try_to_add_help_message(
2584 &self,
2585 root_obligation: &PredicateObligation<'tcx>,
2586 obligation: &PredicateObligation<'tcx>,
2587 trait_predicate: ty::PolyTraitPredicate<'tcx>,
2588 err: &mut Diag<'_>,
2589 span: Span,
2590 is_fn_trait: bool,
2591 suggested: bool,
2592 unsatisfied_const: bool,
2593 ) {
2594 let body_def_id = obligation.cause.body_id;
2595 let span = if let ObligationCauseCode::BinOp { rhs_span: Some(rhs_span), .. } =
2596 obligation.cause.code()
2597 {
2598 *rhs_span
2599 } else {
2600 span
2601 };
2602
2603 let trait_def_id = trait_predicate.def_id();
2605 if is_fn_trait
2606 && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
2607 obligation.param_env,
2608 trait_predicate.self_ty(),
2609 trait_predicate.skip_binder().polarity,
2610 )
2611 {
2612 self.add_help_message_for_fn_trait(trait_predicate, err, implemented_kind, params);
2613 } else if !trait_predicate.has_non_region_infer()
2614 && self.predicate_can_apply(obligation.param_env, trait_predicate)
2615 {
2616 self.suggest_restricting_param_bound(
2624 err,
2625 trait_predicate,
2626 None,
2627 obligation.cause.body_id,
2628 );
2629 } else if trait_def_id.is_local()
2630 && self.tcx.trait_impls_of(trait_def_id).is_empty()
2631 && !self.tcx.trait_is_auto(trait_def_id)
2632 && !self.tcx.trait_is_alias(trait_def_id)
2633 && trait_predicate.polarity() == ty::PredicatePolarity::Positive
2634 {
2635 err.span_help(
2636 self.tcx.def_span(trait_def_id),
2637 crate::fluent_generated::trait_selection_trait_has_no_impls,
2638 );
2639 } else if !suggested
2640 && !unsatisfied_const
2641 && trait_predicate.polarity() == ty::PredicatePolarity::Positive
2642 {
2643 let impl_candidates = self.find_similar_impl_candidates(trait_predicate);
2645 if !self.report_similar_impl_candidates(
2646 &impl_candidates,
2647 trait_predicate,
2648 body_def_id,
2649 err,
2650 true,
2651 obligation.param_env,
2652 ) {
2653 self.report_similar_impl_candidates_for_root_obligation(
2654 obligation,
2655 trait_predicate,
2656 body_def_id,
2657 err,
2658 );
2659 }
2660
2661 self.suggest_convert_to_slice(
2662 err,
2663 obligation,
2664 trait_predicate,
2665 impl_candidates.as_slice(),
2666 span,
2667 );
2668
2669 self.suggest_tuple_wrapping(err, root_obligation, obligation);
2670 }
2671 }
2672
2673 fn add_help_message_for_fn_trait(
2674 &self,
2675 trait_pred: ty::PolyTraitPredicate<'tcx>,
2676 err: &mut Diag<'_>,
2677 implemented_kind: ty::ClosureKind,
2678 params: ty::Binder<'tcx, Ty<'tcx>>,
2679 ) {
2680 let selected_kind = self
2687 .tcx
2688 .fn_trait_kind_from_def_id(trait_pred.def_id())
2689 .expect("expected to map DefId to ClosureKind");
2690 if !implemented_kind.extends(selected_kind) {
2691 err.note(format!(
2692 "`{}` implements `{}`, but it must implement `{}`, which is more general",
2693 trait_pred.skip_binder().self_ty(),
2694 implemented_kind,
2695 selected_kind
2696 ));
2697 }
2698
2699 let given_ty = params.skip_binder();
2701 let expected_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
2702 if let ty::Tuple(given) = given_ty.kind()
2703 && let ty::Tuple(expected) = expected_ty.kind()
2704 {
2705 if expected.len() != given.len() {
2706 err.note(
2708 format!(
2709 "expected a closure taking {} argument{}, but one taking {} argument{} was given",
2710 given.len(),
2711 pluralize!(given.len()),
2712 expected.len(),
2713 pluralize!(expected.len()),
2714 )
2715 );
2716 } else if !self.same_type_modulo_infer(given_ty, expected_ty) {
2717 let (expected_args, given_args) = self.cmp(given_ty, expected_ty);
2719 err.note_expected_found(
2720 &"a closure with arguments",
2721 expected_args,
2722 &"a closure with arguments",
2723 given_args,
2724 );
2725 }
2726 }
2727 }
2728
2729 fn maybe_add_note_for_unsatisfied_const(
2730 &self,
2731 _trait_predicate: ty::PolyTraitPredicate<'tcx>,
2732 _err: &mut Diag<'_>,
2733 _span: Span,
2734 ) -> UnsatisfiedConst {
2735 let unsatisfied_const = UnsatisfiedConst(false);
2736 unsatisfied_const
2738 }
2739
2740 fn report_closure_error(
2741 &self,
2742 obligation: &PredicateObligation<'tcx>,
2743 closure_def_id: DefId,
2744 found_kind: ty::ClosureKind,
2745 kind: ty::ClosureKind,
2746 trait_prefix: &'static str,
2747 ) -> Diag<'a> {
2748 let closure_span = self.tcx.def_span(closure_def_id);
2749
2750 let mut err = ClosureKindMismatch {
2751 closure_span,
2752 expected: kind,
2753 found: found_kind,
2754 cause_span: obligation.cause.span,
2755 trait_prefix,
2756 fn_once_label: None,
2757 fn_mut_label: None,
2758 };
2759
2760 if let Some(typeck_results) = &self.typeck_results {
2763 let hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id.expect_local());
2764 match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
2765 (ty::ClosureKind::FnOnce, Some((span, place))) => {
2766 err.fn_once_label = Some(ClosureFnOnceLabel {
2767 span: *span,
2768 place: ty::place_to_string_for_capture(self.tcx, place),
2769 })
2770 }
2771 (ty::ClosureKind::FnMut, Some((span, place))) => {
2772 err.fn_mut_label = Some(ClosureFnMutLabel {
2773 span: *span,
2774 place: ty::place_to_string_for_capture(self.tcx, place),
2775 })
2776 }
2777 _ => {}
2778 }
2779 }
2780
2781 self.dcx().create_err(err)
2782 }
2783
2784 fn report_cyclic_signature_error(
2785 &self,
2786 obligation: &PredicateObligation<'tcx>,
2787 found_trait_ref: ty::TraitRef<'tcx>,
2788 expected_trait_ref: ty::TraitRef<'tcx>,
2789 terr: TypeError<'tcx>,
2790 ) -> Diag<'a> {
2791 let self_ty = found_trait_ref.self_ty();
2792 let (cause, terr) = if let ty::Closure(def_id, _) = self_ty.kind() {
2793 (
2794 ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
2795 TypeError::CyclicTy(self_ty),
2796 )
2797 } else {
2798 (obligation.cause.clone(), terr)
2799 };
2800 self.report_and_explain_type_error(
2801 TypeTrace::trait_refs(&cause, expected_trait_ref, found_trait_ref),
2802 obligation.param_env,
2803 terr,
2804 )
2805 }
2806
2807 fn report_opaque_type_auto_trait_leakage(
2808 &self,
2809 obligation: &PredicateObligation<'tcx>,
2810 def_id: DefId,
2811 ) -> ErrorGuaranteed {
2812 let name = match self.tcx.local_opaque_ty_origin(def_id.expect_local()) {
2813 hir::OpaqueTyOrigin::FnReturn { .. } | hir::OpaqueTyOrigin::AsyncFn { .. } => {
2814 "opaque type".to_string()
2815 }
2816 hir::OpaqueTyOrigin::TyAlias { .. } => {
2817 format!("`{}`", self.tcx.def_path_debug_str(def_id))
2818 }
2819 };
2820 let mut err = self.dcx().struct_span_err(
2821 obligation.cause.span,
2822 format!("cannot check whether the hidden type of {name} satisfies auto traits"),
2823 );
2824
2825 err.note(
2826 "fetching the hidden types of an opaque inside of the defining scope is not supported. \
2827 You can try moving the opaque type and the item that actually registers a hidden type into a new submodule",
2828 );
2829 err.span_note(self.tcx.def_span(def_id), "opaque type is declared here");
2830
2831 self.note_obligation_cause(&mut err, &obligation);
2832 self.dcx().try_steal_replace_and_emit_err(self.tcx.def_span(def_id), StashKey::Cycle, err)
2833 }
2834
2835 fn report_signature_mismatch_error(
2836 &self,
2837 obligation: &PredicateObligation<'tcx>,
2838 span: Span,
2839 found_trait_ref: ty::TraitRef<'tcx>,
2840 expected_trait_ref: ty::TraitRef<'tcx>,
2841 ) -> Result<Diag<'a>, ErrorGuaranteed> {
2842 let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
2843 let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
2844
2845 expected_trait_ref.self_ty().error_reported()?;
2846 let found_trait_ty = found_trait_ref.self_ty();
2847
2848 let found_did = match *found_trait_ty.kind() {
2849 ty::Closure(did, _) | ty::FnDef(did, _) | ty::Coroutine(did, ..) => Some(did),
2850 _ => None,
2851 };
2852
2853 let found_node = found_did.and_then(|did| self.tcx.hir().get_if_local(did));
2854 let found_span = found_did.and_then(|did| self.tcx.hir().span_if_local(did));
2855
2856 if !self.reported_signature_mismatch.borrow_mut().insert((span, found_span)) {
2857 return Err(self.dcx().span_delayed_bug(span, "already_reported"));
2860 }
2861
2862 let mut not_tupled = false;
2863
2864 let found = match found_trait_ref.args.type_at(1).kind() {
2865 ty::Tuple(tys) => vec![ArgKind::empty(); tys.len()],
2866 _ => {
2867 not_tupled = true;
2868 vec![ArgKind::empty()]
2869 }
2870 };
2871
2872 let expected_ty = expected_trait_ref.args.type_at(1);
2873 let expected = match expected_ty.kind() {
2874 ty::Tuple(tys) => {
2875 tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
2876 }
2877 _ => {
2878 not_tupled = true;
2879 vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())]
2880 }
2881 };
2882
2883 if Some(expected_trait_ref.def_id) != self.tcx.lang_items().coroutine_trait() && not_tupled
2889 {
2890 return Ok(self.report_and_explain_type_error(
2891 TypeTrace::trait_refs(&obligation.cause, expected_trait_ref, found_trait_ref),
2892 obligation.param_env,
2893 ty::error::TypeError::Mismatch,
2894 ));
2895 }
2896 if found.len() != expected.len() {
2897 let (closure_span, closure_arg_span, found) = found_did
2898 .and_then(|did| {
2899 let node = self.tcx.hir().get_if_local(did)?;
2900 let (found_span, closure_arg_span, found) = self.get_fn_like_arguments(node)?;
2901 Some((Some(found_span), closure_arg_span, found))
2902 })
2903 .unwrap_or((found_span, None, found));
2904
2905 if found.len() != expected.len() {
2911 return Ok(self.report_arg_count_mismatch(
2912 span,
2913 closure_span,
2914 expected,
2915 found,
2916 found_trait_ty.is_closure(),
2917 closure_arg_span,
2918 ));
2919 }
2920 }
2921 Ok(self.report_closure_arg_mismatch(
2922 span,
2923 found_span,
2924 found_trait_ref,
2925 expected_trait_ref,
2926 obligation.cause.code(),
2927 found_node,
2928 obligation.param_env,
2929 ))
2930 }
2931
2932 pub fn get_fn_like_arguments(
2937 &self,
2938 node: Node<'_>,
2939 ) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
2940 let sm = self.tcx.sess.source_map();
2941 let hir = self.tcx.hir();
2942 Some(match node {
2943 Node::Expr(&hir::Expr {
2944 kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
2945 ..
2946 }) => (
2947 fn_decl_span,
2948 fn_arg_span,
2949 hir.body(body)
2950 .params
2951 .iter()
2952 .map(|arg| {
2953 if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat
2954 {
2955 Some(ArgKind::Tuple(
2956 Some(span),
2957 args.iter()
2958 .map(|pat| {
2959 sm.span_to_snippet(pat.span)
2960 .ok()
2961 .map(|snippet| (snippet, "_".to_owned()))
2962 })
2963 .collect::<Option<Vec<_>>>()?,
2964 ))
2965 } else {
2966 let name = sm.span_to_snippet(arg.pat.span).ok()?;
2967 Some(ArgKind::Arg(name, "_".to_owned()))
2968 }
2969 })
2970 .collect::<Option<Vec<ArgKind>>>()?,
2971 ),
2972 Node::Item(&hir::Item { kind: hir::ItemKind::Fn { ref sig, .. }, .. })
2973 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
2974 | Node::TraitItem(&hir::TraitItem {
2975 kind: hir::TraitItemKind::Fn(ref sig, _), ..
2976 })
2977 | Node::ForeignItem(&hir::ForeignItem {
2978 kind: hir::ForeignItemKind::Fn(ref sig, _, _),
2979 ..
2980 }) => (
2981 sig.span,
2982 None,
2983 sig.decl
2984 .inputs
2985 .iter()
2986 .map(|arg| match arg.kind {
2987 hir::TyKind::Tup(tys) => ArgKind::Tuple(
2988 Some(arg.span),
2989 vec![("_".to_owned(), "_".to_owned()); tys.len()],
2990 ),
2991 _ => ArgKind::empty(),
2992 })
2993 .collect::<Vec<ArgKind>>(),
2994 ),
2995 Node::Ctor(variant_data) => {
2996 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| hir.span(id));
2997 (span, None, vec![ArgKind::empty(); variant_data.fields().len()])
2998 }
2999 _ => panic!("non-FnLike node found: {node:?}"),
3000 })
3001 }
3002
3003 pub fn report_arg_count_mismatch(
3007 &self,
3008 span: Span,
3009 found_span: Option<Span>,
3010 expected_args: Vec<ArgKind>,
3011 found_args: Vec<ArgKind>,
3012 is_closure: bool,
3013 closure_arg_span: Option<Span>,
3014 ) -> Diag<'a> {
3015 let kind = if is_closure { "closure" } else { "function" };
3016
3017 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
3018 let arg_length = arguments.len();
3019 let distinct = matches!(other, &[ArgKind::Tuple(..)]);
3020 match (arg_length, arguments.get(0)) {
3021 (1, Some(ArgKind::Tuple(_, fields))) => {
3022 format!("a single {}-tuple as argument", fields.len())
3023 }
3024 _ => format!(
3025 "{} {}argument{}",
3026 arg_length,
3027 if distinct && arg_length > 1 { "distinct " } else { "" },
3028 pluralize!(arg_length)
3029 ),
3030 }
3031 };
3032
3033 let expected_str = args_str(&expected_args, &found_args);
3034 let found_str = args_str(&found_args, &expected_args);
3035
3036 let mut err = struct_span_code_err!(
3037 self.dcx(),
3038 span,
3039 E0593,
3040 "{} is expected to take {}, but it takes {}",
3041 kind,
3042 expected_str,
3043 found_str,
3044 );
3045
3046 err.span_label(span, format!("expected {kind} that takes {expected_str}"));
3047
3048 if let Some(found_span) = found_span {
3049 err.span_label(found_span, format!("takes {found_str}"));
3050
3051 if found_args.is_empty() && is_closure {
3055 let underscores = vec!["_"; expected_args.len()].join(", ");
3056 err.span_suggestion_verbose(
3057 closure_arg_span.unwrap_or(found_span),
3058 format!(
3059 "consider changing the closure to take and ignore the expected argument{}",
3060 pluralize!(expected_args.len())
3061 ),
3062 format!("|{underscores}|"),
3063 Applicability::MachineApplicable,
3064 );
3065 }
3066
3067 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
3068 if fields.len() == expected_args.len() {
3069 let sugg = fields
3070 .iter()
3071 .map(|(name, _)| name.to_owned())
3072 .collect::<Vec<String>>()
3073 .join(", ");
3074 err.span_suggestion_verbose(
3075 found_span,
3076 "change the closure to take multiple arguments instead of a single tuple",
3077 format!("|{sugg}|"),
3078 Applicability::MachineApplicable,
3079 );
3080 }
3081 }
3082 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
3083 && fields.len() == found_args.len()
3084 && is_closure
3085 {
3086 let sugg = format!(
3087 "|({}){}|",
3088 found_args
3089 .iter()
3090 .map(|arg| match arg {
3091 ArgKind::Arg(name, _) => name.to_owned(),
3092 _ => "_".to_owned(),
3093 })
3094 .collect::<Vec<String>>()
3095 .join(", "),
3096 if found_args.iter().any(|arg| match arg {
3098 ArgKind::Arg(_, ty) => ty != "_",
3099 _ => false,
3100 }) {
3101 format!(
3102 ": ({})",
3103 fields
3104 .iter()
3105 .map(|(_, ty)| ty.to_owned())
3106 .collect::<Vec<String>>()
3107 .join(", ")
3108 )
3109 } else {
3110 String::new()
3111 },
3112 );
3113 err.span_suggestion_verbose(
3114 found_span,
3115 "change the closure to accept a tuple instead of individual arguments",
3116 sugg,
3117 Applicability::MachineApplicable,
3118 );
3119 }
3120 }
3121
3122 err
3123 }
3124
3125 pub fn type_implements_fn_trait(
3129 &self,
3130 param_env: ty::ParamEnv<'tcx>,
3131 ty: ty::Binder<'tcx, Ty<'tcx>>,
3132 polarity: ty::PredicatePolarity,
3133 ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
3134 self.commit_if_ok(|_| {
3135 for trait_def_id in [
3136 self.tcx.lang_items().fn_trait(),
3137 self.tcx.lang_items().fn_mut_trait(),
3138 self.tcx.lang_items().fn_once_trait(),
3139 ] {
3140 let Some(trait_def_id) = trait_def_id else { continue };
3141 let var = self.next_ty_var(DUMMY_SP);
3144 let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
3146 let obligation = Obligation::new(
3147 self.tcx,
3148 ObligationCause::dummy(),
3149 param_env,
3150 ty.rebind(ty::TraitPredicate { trait_ref, polarity }),
3151 );
3152 let ocx = ObligationCtxt::new(self);
3153 ocx.register_obligation(obligation);
3154 if ocx.select_all_or_error().is_empty() {
3155 return Ok((
3156 self.tcx
3157 .fn_trait_kind_from_def_id(trait_def_id)
3158 .expect("expected to map DefId to ClosureKind"),
3159 ty.rebind(self.resolve_vars_if_possible(var)),
3160 ));
3161 }
3162 }
3163
3164 Err(())
3165 })
3166 }
3167
3168 fn report_not_const_evaluatable_error(
3169 &self,
3170 obligation: &PredicateObligation<'tcx>,
3171 span: Span,
3172 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3173 if !self.tcx.features().generic_const_exprs() {
3174 let guar = self
3175 .dcx()
3176 .struct_span_err(span, "constant expression depends on a generic parameter")
3177 .with_note("this may fail depending on what value the parameter takes")
3184 .emit();
3185 return Err(guar);
3186 }
3187
3188 match obligation.predicate.kind().skip_binder() {
3189 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => match ct.kind() {
3190 ty::ConstKind::Unevaluated(uv) => {
3191 let mut err =
3192 self.dcx().struct_span_err(span, "unconstrained generic constant");
3193 let const_span = self.tcx.def_span(uv.def);
3194
3195 let const_ty = self.tcx.type_of(uv.def).instantiate(self.tcx, uv.args);
3196 let cast = if const_ty != self.tcx.types.usize { " as usize" } else { "" };
3197 let msg = "try adding a `where` bound";
3198 match self.tcx.sess.source_map().span_to_snippet(const_span) {
3199 Ok(snippet) => {
3200 let code = format!("[(); {snippet}{cast}]:");
3201 let def_id = if let ObligationCauseCode::CompareImplItem {
3202 trait_item_def_id,
3203 ..
3204 } = obligation.cause.code()
3205 {
3206 trait_item_def_id.as_local()
3207 } else {
3208 Some(obligation.cause.body_id)
3209 };
3210 if let Some(def_id) = def_id
3211 && let Some(generics) = self.tcx.hir().get_generics(def_id)
3212 {
3213 err.span_suggestion_verbose(
3214 generics.tail_span_for_predicate_suggestion(),
3215 msg,
3216 format!("{} {code}", generics.add_where_or_trailing_comma()),
3217 Applicability::MaybeIncorrect,
3218 );
3219 } else {
3220 err.help(format!("{msg}: where {code}"));
3221 };
3222 }
3223 _ => {
3224 err.help(msg);
3225 }
3226 };
3227 Ok(err)
3228 }
3229 ty::ConstKind::Expr(_) => {
3230 let err = self
3231 .dcx()
3232 .struct_span_err(span, format!("unconstrained generic constant `{ct}`"));
3233 Ok(err)
3234 }
3235 _ => {
3236 bug!("const evaluatable failed for non-unevaluated const `{ct:?}`");
3237 }
3238 },
3239 _ => {
3240 span_bug!(
3241 span,
3242 "unexpected non-ConstEvaluatable predicate, this should not be reachable"
3243 )
3244 }
3245 }
3246 }
3247}