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