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