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