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