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