1use core::ops::ControlFlow;
3use std::borrow::Cow;
4use std::collections::hash_set;
5use std::path::PathBuf;
6
7use rustc_ast::ast::LitKind;
8use rustc_ast::{LitIntType, TraitObjectSyntax};
9use rustc_attr_ir::diagnostic::CustomDiagnostic;
10use rustc_attr_ir::find_attr;
11use rustc_attr_ir::lang_items::LangItem;
12use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13use rustc_data_structures::unord::UnordSet;
14use rustc_errors::codes::*;
15use rustc_errors::{
16 Applicability, Diag, ErrorGuaranteed, MultiSpan, StringPart, Sublevel, msg, pluralize,
17 struct_span_code_err,
18};
19use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
20use rustc_hir::intravisit::Visitor;
21use rustc_hir::{self as hir, Node, expr_needs_parens};
22use rustc_infer::infer::{InferOk, TypeTrace};
23use rustc_infer::traits::solve::Goal;
24use rustc_infer::traits::{ImplSource, TraitErrors, WellFormedLoc};
25use rustc_middle::traits::SignatureMismatchData;
26use rustc_middle::traits::select::OverflowError;
27use rustc_middle::ty::abstract_const::NotConstEvaluatable;
28use rustc_middle::ty::error::{ExpectedFound, TypeError};
29use rustc_middle::ty::print::{
30 PrintPolyTraitClauseExt, PrintPolyTraitRefExt as _, PrintTraitClauseExt as _,
31 PrintTraitRefExt as _, with_forced_trimmed_paths,
32};
33use rustc_middle::ty::transmute::{Answer, Reason};
34use rustc_middle::ty::{
35 self, ConstKind, GenericArgKind, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeFoldable,
36 TypeFolder, TypeSuperFoldable, TypeVisitableExt, Unnormalized, Upcast,
37};
38use rustc_span::def_id::CrateNum;
39use rustc_span::{BytePos, DUMMY_SP, STDLIB_STABLE_CRATES, Span, Symbol, bug, span_bug, sym};
40use tracing::{debug, instrument};
41
42use super::suggestions::get_explanation_based_on_obligation;
43use super::{ArgKind, CandidateSimilarity, GetSafeTransmuteErrorAndReason, ImplCandidate};
44use crate::diagnostics::{
45 AssocTypeWithSameName, ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch,
46 CoroClosureNotFn, RefToFnOnce,
47};
48use crate::error_reporting::TypeErrCtxt;
49use crate::error_reporting::infer::TyCategory;
50use crate::error_reporting::traits::suggestions::ReturnsVisitor;
51use crate::error_reporting::traits::{FindExprBySpan, report_dyn_incompatibility};
52use crate::infer::{self, InferCtxt, InferCtxtExt as _};
53use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
54use crate::traits::{
55 MismatchedProjectionTypes, NormalizeExt, Obligation, ObligationCause, ObligationCauseCode,
56 ObligationCtxt, PredicateObligation, SelectionContext, SelectionError, elaborate,
57 specialization_graph,
58};
59
60impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
61 fn is_explicit_self_trait_bound_on_impl_assoc_type(
63 &self,
64 body_def_id: LocalDefId,
65 cause_code: &ObligationCauseCode<'tcx>,
66 trait_def_id: DefId,
67 ) -> bool {
68 let ObligationCauseCode::WhereClause(item_def_id, span) = *cause_code.peel_derives() else {
69 return false;
70 };
71 if !self.tcx.opt_associated_item(body_def_id.to_def_id()).is_some_and(|assoc_item| {
73 assoc_item.trait_item_def_id().is_some_and(|trait_item_def_id| {
74 trait_item_def_id == item_def_id
75 && #[allow(non_exhaustive_omitted_patterns)] match assoc_item.kind {
ty::AssocKind::Type { .. } => true,
_ => false,
}matches!(assoc_item.kind, ty::AssocKind::Type { .. })
76 })
77 }) {
78 return false;
79 }
80
81 self.tcx.clauses_of(item_def_id).instantiate_own_identity().any(|(clause, clause_span)| {
82 clause_span == span
83 && clause.skip_norm_wip().as_trait_clause().is_some_and(|trait_pred| {
84 trait_pred.def_id() == trait_def_id
85 && trait_pred.skip_binder().self_ty().is_self_param()
86 })
87 })
88 }
89
90 pub fn report_selection_error(
94 &self,
95 mut obligation: PredicateObligation<'tcx>,
96 root_obligation: &PredicateObligation<'tcx>,
97 error: &SelectionError<'tcx>,
98 ) -> ErrorGuaranteed {
99 let tcx = self.tcx;
100 let mut span = obligation.cause.span;
101 let mut long_ty_file = None;
102
103 let mut err = match *error {
104 SelectionError::Unimplemented => {
105 if let ObligationCauseCode::WellFormed(wf_loc) =
108 root_obligation.cause.code().peel_derives()
109 && !obligation.predicate.has_non_region_infer()
110 && !#[allow(non_exhaustive_omitted_patterns)] match wf_loc {
WellFormedLoc::None => true,
_ => false,
}matches!(wf_loc, WellFormedLoc::None)
111 {
112 if let Some(cause) = self.tcx.diagnostic_hir_wf_check((
113 tcx.erase_and_anonymize_regions(obligation.predicate),
114 *wf_loc,
115 )) {
116 obligation.cause = cause.clone();
117 span = obligation.cause.span;
118 }
119 }
120
121 if let ObligationCauseCode::CompareImplItem {
122 impl_item_def_id,
123 trait_item_def_id,
124 kind: _,
125 } = *obligation.cause.code()
126 {
127 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs:127",
"rustc_trait_selection::error_reporting::traits::fulfillment_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
::tracing_core::__macro_support::Option::Some(127u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::fulfillment_errors"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("ObligationCauseCode::CompareImplItemObligation")
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("ObligationCauseCode::CompareImplItemObligation");
128 return self
129 .report_extra_impl_obligation(
130 span,
131 impl_item_def_id,
132 trait_item_def_id,
133 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", obligation.predicate))
})format!("`{}`", obligation.predicate),
134 )
135 .emit_err();
136 }
137
138 match *obligation.cause.code().peel_derives() {
140 ObligationCauseCode::ConstParam(ty) => {
141 return self
142 .report_const_param_ty_error(
143 ty,
144 self.tcx.ty_span(obligation.cause.body_def_id),
145 &obligation,
146 )
147 .emit_err();
148 }
149 ObligationCauseCode::ConstItemTy(ty) => {
150 return self
151 .report_const_param_ty_error(ty, obligation.cause.span, &obligation)
152 .emit_err();
153 }
154 _ => {}
155 }
156
157 let bound_predicate = obligation.predicate.kind();
158 match bound_predicate.skip_binder() {
159 ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_predicate)) => {
160 let leaf_trait_predicate = self.deeply_resolve_ignoring_regions(
161 bound_predicate.rebind(trait_predicate),
162 );
163
164 let (main_trait_predicate, main_obligation) =
171 if let ty::PredicateKind::Clause(
172 ty::ClauseKind::Trait(root_pred)
173 ) = root_obligation.predicate.kind().skip_binder()
174 && !leaf_trait_predicate.self_ty().skip_binder().has_escaping_bound_vars()
175 && !root_pred.self_ty().has_escaping_bound_vars()
176 && (
181 self.can_eq(
183 obligation.param_env,
184 leaf_trait_predicate.self_ty().skip_binder(),
185 root_pred.self_ty().peel_refs(),
186 )
187 || self.can_eq(
189 obligation.param_env,
190 leaf_trait_predicate.self_ty().skip_binder(),
191 root_pred.self_ty(),
192 )
193 )
194 && leaf_trait_predicate.def_id() != root_pred.def_id()
198 && !self.tcx.is_lang_item(root_pred.def_id(), LangItem::CoerceUnsized)
201 && !self.tcx.is_lang_item(root_pred.def_id(), LangItem::Unsize)
204 {
205 (
206 self.deeply_resolve_ignoring_regions(
207 root_obligation.predicate.kind().rebind(root_pred),
208 ),
209 root_obligation,
210 )
211 } else {
212 (leaf_trait_predicate, &obligation)
213 };
214
215 if let Some(guar) = self
216 .emit_specialized_closure_kind_error(&obligation, leaf_trait_predicate)
217 {
218 return guar;
219 }
220
221 if let Err(guar) = leaf_trait_predicate.error_reported() {
222 return guar;
223 }
224 if self.is_explicit_self_trait_bound_on_impl_assoc_type(
225 obligation.cause.body_def_id,
226 obligation.cause.code(),
227 leaf_trait_predicate.def_id(),
228 ) && let ty::Param(param_ty) =
229 *leaf_trait_predicate.skip_binder().self_ty().kind()
230 {
231 span = param_ty.span_from_generics(
232 self.tcx,
233 obligation.cause.body_def_id.to_def_id(),
234 );
235 }
236 if let Err(guar) = self.fn_arg_obligation(&obligation) {
239 return guar;
240 }
241 let (post_message, pre_message, type_def) = self
242 .get_parent_trait_ref(obligation.cause.code())
243 .map(|(t, s)| {
244 let t = self.tcx.short_string(t, &mut long_ty_file);
245 (
246 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" in `{0}`", t))
})format!(" in `{t}`"),
247 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("within `{0}`, ", t))
})format!("within `{t}`, "),
248 s.map(|s| (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("within this `{0}`", t))
})format!("within this `{t}`"), s)),
249 )
250 })
251 .unwrap_or_default();
252
253 let CustomDiagnostic { message, label, notes, parent_label } = self
254 .on_unimplemented_note(
255 main_trait_predicate,
256 main_obligation,
257 &mut long_ty_file,
258 );
259
260 let have_alt_message = message.is_some() || label.is_some();
261
262 let message = message.unwrap_or_else(|| {
263 self.get_standard_error_message(
264 main_trait_predicate,
265 None,
266 post_message,
267 &mut long_ty_file,
268 )
269 });
270 let is_try_conversion =
271 self.is_try_conversion(span, main_trait_predicate.def_id());
272 let is_question_mark = #[allow(non_exhaustive_omitted_patterns)] match root_obligation.cause.code().peel_derives()
{
ObligationCauseCode::QuestionMark => true,
_ => false,
}matches!(
273 root_obligation.cause.code().peel_derives(),
274 ObligationCauseCode::QuestionMark,
275 ) && !(self
276 .tcx
277 .is_diagnostic_item(sym::FromResidual, main_trait_predicate.def_id())
278 || self.tcx.is_lang_item(main_trait_predicate.def_id(), LangItem::Try));
279 let is_unsize =
280 self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Unsize);
281 let question_mark_message = "the question mark operation (`?`) implicitly \
282 performs a conversion on the error value \
283 using the `From` trait";
284 let (message, notes) = if is_try_conversion {
285 let ty = self.tcx.short_string(
286 main_trait_predicate.skip_binder().self_ty(),
287 &mut long_ty_file,
288 );
289 (
291 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`?` couldn\'t convert the error to `{0}`",
ty))
})format!("`?` couldn't convert the error to `{ty}`"),
292 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[question_mark_message.to_owned()]))vec![question_mark_message.to_owned()],
293 )
294 } else if is_question_mark {
295 let main_trait_predicate =
296 self.tcx.short_string(main_trait_predicate, &mut long_ty_file);
297 (
301 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`?` couldn\'t convert the error: `{0}` is not satisfied",
main_trait_predicate))
})format!(
302 "`?` couldn't convert the error: `{main_trait_predicate}` is \
303 not satisfied",
304 ),
305 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[question_mark_message.to_owned()]))vec![question_mark_message.to_owned()],
306 )
307 } else {
308 (message, notes)
309 };
310
311 let (err_msg, safe_transmute_explanation) = if self
312 .tcx
313 .is_lang_item(main_trait_predicate.def_id(), LangItem::TransmuteTrait)
314 {
315 let (report_obligation, report_pred) = self
317 .select_transmute_obligation_for_reporting(
318 &obligation,
319 main_trait_predicate,
320 root_obligation,
321 );
322
323 match self.get_safe_transmute_error_and_reason(
324 report_obligation,
325 report_pred,
326 span,
327 ) {
328 GetSafeTransmuteErrorAndReason::Silent => {
329 return self
330 .dcx()
331 .span_delayed_bug(span, "silent safe transmute error");
332 }
333 GetSafeTransmuteErrorAndReason::Default => (message, None),
334 GetSafeTransmuteErrorAndReason::Error {
335 err_msg,
336 safe_transmute_explanation,
337 } => (err_msg, safe_transmute_explanation),
338 }
339 } else {
340 (message, None)
341 };
342
343 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", err_msg))
})).with_code(E0277)
}struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg);
344
345 let trait_def_id = main_trait_predicate.def_id();
346 let leaf_trait_def_id = leaf_trait_predicate.def_id();
347 if (self.tcx.is_diagnostic_item(sym::From, trait_def_id)
348 || self.tcx.is_diagnostic_item(sym::TryFrom, trait_def_id))
349 && (self.tcx.is_diagnostic_item(sym::From, leaf_trait_def_id)
350 || self.tcx.is_diagnostic_item(sym::TryFrom, leaf_trait_def_id))
351 && let Some(trait_ref) =
352 leaf_trait_predicate.no_bound_vars().map(|pred| pred.trait_ref)
353 && let Some(found_ty) =
354 trait_ref.args.get(1).and_then(|arg| arg.as_type())
355 && let Some(ty) =
356 main_trait_predicate.no_bound_vars().map(|pred| pred.self_ty())
357 && let Some(cast_ty) =
358 self.find_explicit_cast_type(obligation.param_env, found_ty, ty)
359 {
360 let found_ty_str = self.tcx.short_string(found_ty, &mut long_ty_file);
361 let cast_ty_str = self.tcx.short_string(cast_ty, &mut long_ty_file);
362
363 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider casting the `{0}` value to `{1}`",
found_ty_str, cast_ty_str))
})format!(
364 "consider casting the `{found_ty_str}` value to `{cast_ty_str}`",
365 ));
366 }
367
368 *err.long_ty_path() = long_ty_file;
369
370 let mut suggested = false;
371 let mut noted_missing_impl = false;
372 if is_try_conversion || is_question_mark {
373 (suggested, noted_missing_impl) = self.try_conversion_context(
374 &obligation,
375 main_trait_predicate,
376 &mut err,
377 );
378 }
379
380 suggested |= self.detect_negative_literal(
381 &obligation,
382 main_trait_predicate,
383 &mut err,
384 );
385
386 if let Some(ret_span) = self.return_type_span(&obligation) {
387 if is_try_conversion {
388 let ty = self.tcx.short_string(
389 main_trait_predicate.skip_binder().self_ty(),
390 err.long_ty_path(),
391 );
392 err.span_label(
393 ret_span,
394 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` because of this",
ty))
})format!("expected `{ty}` because of this"),
395 );
396 } else if is_question_mark {
397 let main_trait_predicate =
398 self.tcx.short_string(main_trait_predicate, err.long_ty_path());
399 err.span_label(
400 ret_span,
401 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("required `{0}` because of this",
main_trait_predicate))
})format!("required `{main_trait_predicate}` because of this"),
402 );
403 }
404 }
405
406 if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Tuple) {
407 self.add_tuple_trait_message(
408 obligation.cause.code().peel_derives(),
409 &mut err,
410 );
411 }
412
413 let explanation = get_explanation_based_on_obligation(
414 self.tcx,
415 &obligation,
416 leaf_trait_predicate,
417 pre_message,
418 err.long_ty_path(),
419 );
420
421 self.check_for_binding_assigned_block_without_tail_expression(
422 &obligation,
423 &mut err,
424 leaf_trait_predicate,
425 );
426 self.suggest_add_result_as_return_type(
427 &obligation,
428 &mut err,
429 leaf_trait_predicate,
430 );
431
432 if self.suggest_add_reference_to_arg(
433 &obligation,
434 &mut err,
435 leaf_trait_predicate,
436 have_alt_message,
437 ) {
438 self.note_obligation_cause(&mut err, &obligation);
439 return err.emit_err();
440 }
441
442 let ty_span = match leaf_trait_predicate.self_ty().skip_binder().kind() {
443 ty::Adt(def, _)
444 if def.did().is_local()
445 && !self
446 .can_suggest_derive(&obligation, leaf_trait_predicate) =>
447 {
448 self.tcx.def_span(def.did())
449 }
450 ty::Closure(def_id, _) => self.tcx.def_span(*def_id),
451 _ => DUMMY_SP,
452 };
453 if let Some(s) = label {
454 err.span_label(span, s);
457 if !#[allow(non_exhaustive_omitted_patterns)] match leaf_trait_predicate.skip_binder().self_ty().kind()
{
ty::Param(_) => true,
_ => false,
}matches!(leaf_trait_predicate.skip_binder().self_ty().kind(), ty::Param(_))
458 && !self.tcx.is_diagnostic_item(sym::FromResidual, leaf_trait_predicate.def_id())
462 {
465 if ty_span == DUMMY_SP {
468 err.help(explanation);
469 } else {
470 err.span_help(ty_span, explanation);
471 }
472 }
473 } else if let Some(custom_explanation) = safe_transmute_explanation {
474 err.span_label(span, custom_explanation);
475 } else if (explanation.len() > self.tcx.sess.diagnostic_width()
476 || ty_span != DUMMY_SP)
477 && !noted_missing_impl
478 {
479 err.span_label(span, "unsatisfied trait bound");
482
483 if ty_span == DUMMY_SP {
486 err.help(explanation);
487 } else {
488 err.span_help(ty_span, explanation);
489 }
490 } else {
491 err.span_label(span, explanation);
492 }
493
494 if let ObligationCauseCode::Coercion { source, target } =
495 *obligation.cause.code().peel_derives()
496 {
497 if self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Sized)
498 {
499 self.suggest_borrowing_for_object_cast(
500 &mut err,
501 root_obligation,
502 source,
503 target,
504 );
505 }
506 }
507
508 if let Some((msg, span)) = type_def {
509 err.span_label(span, msg);
510 }
511 let derive_suggestion_will_be_shown = main_trait_predicate
519 == leaf_trait_predicate
520 && self.can_suggest_derive(&obligation, leaf_trait_predicate);
521 if !derive_suggestion_will_be_shown {
522 for note in notes {
523 err.note(note);
526 }
527 }
528 if let Some(s) = parent_label {
529 let body = obligation.cause.body_def_id;
530 err.span_label(tcx.def_span(body), s);
531 }
532
533 self.suggest_floating_point_literal(
534 &obligation,
535 &mut err,
536 leaf_trait_predicate,
537 );
538 self.suggest_dereferencing_index(
539 &obligation,
540 &mut err,
541 leaf_trait_predicate,
542 );
543 suggested |=
544 self.suggest_dereferences(&obligation, &mut err, leaf_trait_predicate)
545 || self.suggest_remove_reference(
546 &obligation,
547 &mut err,
548 leaf_trait_predicate,
549 );
550
551 suggested |=
552 self.suggest_fn_call(&obligation, &mut err, leaf_trait_predicate);
553 suggested |= self.suggest_cast_to_fn_pointer(
554 &obligation,
555 &mut err,
556 leaf_trait_predicate,
557 main_trait_predicate,
558 span,
559 );
560
561 suggested |= self.suggest_semicolon_removal(
562 &obligation,
563 &mut err,
564 span,
565 leaf_trait_predicate,
566 );
567 self.note_different_trait_with_same_name(
568 &mut err,
569 &obligation,
570 leaf_trait_predicate,
571 );
572 self.note_adt_version_mismatch(&mut err, leaf_trait_predicate);
573 self.suggest_remove_await(&obligation, &mut err);
574 self.suggest_derive(&obligation, &mut err, leaf_trait_predicate);
575
576 if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Try) {
577 self.suggest_await_before_try(
578 &mut err,
579 &obligation,
580 leaf_trait_predicate,
581 span,
582 );
583 }
584
585 if self.suggest_add_clone_to_arg(
586 &obligation,
587 &mut err,
588 leaf_trait_predicate,
589 ) {
590 return err.emit_err();
591 }
592
593 if self.suggest_impl_trait(&mut err, &obligation, leaf_trait_predicate) {
594 return err.emit_err();
595 }
596
597 if is_unsize {
598 err.note(
601 "all implementations of `Unsize` are provided \
602 automatically by the compiler, see \
603 <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
604 for more information",
605 );
606 }
607
608 let is_fn_trait = tcx.is_fn_trait(leaf_trait_predicate.def_id());
609 let is_target_feature_fn = if let ty::FnDef(def_id, _) =
610 *leaf_trait_predicate.skip_binder().self_ty().kind()
611 {
612 !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
613 } else {
614 false
615 };
616 if is_fn_trait && is_target_feature_fn {
617 err.note(
618 "`#[target_feature(..)]` functions do not implement the `Fn` traits",
619 );
620 err.note(
621 "try casting the function to a `fn` pointer or wrapping it in a closure",
622 );
623 }
624
625 self.note_field_shadowed_by_private_candidate_in_cause(
626 &mut err,
627 &obligation.cause,
628 obligation.param_env,
629 );
630 self.try_to_add_help_message(
631 &root_obligation,
632 &obligation,
633 leaf_trait_predicate,
634 &mut err,
635 span,
636 is_fn_trait,
637 suggested,
638 );
639
640 if !is_unsize {
643 self.suggest_change_mut(&obligation, &mut err, leaf_trait_predicate);
644 }
645
646 if leaf_trait_predicate.skip_binder().self_ty().is_never()
651 && self.diverging_fallback_has_occurred
652 {
653 let predicate = leaf_trait_predicate.map_bound(|trait_pred| {
654 trait_pred.with_replaced_self_ty(self.tcx, tcx.types.unit)
655 });
656 let unit_obligation = obligation.with(tcx, predicate);
657 if self.predicate_may_hold(&unit_obligation) {
658 err.note(
659 "this error might have been caused by changes to \
660 Rust's type-inference algorithm (see issue #148922 \
661 <https://github.com/rust-lang/rust/issues/148922> \
662 for more information)",
663 );
664 err.help(
665 "you might have intended to use the type `()` here instead",
666 );
667 }
668 }
669
670 self.explain_hrtb_projection(
671 &mut err,
672 leaf_trait_predicate,
673 obligation.param_env,
674 &obligation.cause,
675 );
676 self.suggest_desugaring_async_fn_in_trait(&mut err, main_trait_predicate);
677
678 let in_std_macro =
684 match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
685 Some(macro_def_id) => {
686 let crate_name = tcx.crate_name(macro_def_id.krate);
687 STDLIB_STABLE_CRATES.contains(&crate_name)
688 }
689 None => false,
690 };
691
692 if in_std_macro
693 && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id())
{
Some(sym::Debug | sym::Display) => true,
_ => false,
}matches!(
694 self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id()),
695 Some(sym::Debug | sym::Display)
696 )
697 {
698 return err.emit_err();
699 }
700
701 err
702 }
703
704 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(clause)) => self
705 .report_host_effect_error(
706 bound_predicate.rebind(clause),
707 &obligation,
708 span,
709 ),
710
711 ty::PredicateKind::Subtype(predicate) => {
712 ::rustc_span::macros::bug_impl(Some(span),
format_args!("subtype requirement gave wrong error: `{0:?}`", predicate),
Location::caller())span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
716 }
717
718 ty::PredicateKind::Coerce(predicate) => {
719 ::rustc_span::macros::bug_impl(Some(span),
format_args!("coerce requirement gave wrong error: `{0:?}`", predicate),
Location::caller())span_bug!(span, "coerce requirement gave wrong error: `{:?}`", predicate)
723 }
724
725 ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..))
726 if self.next_trait_solver() =>
727 {
728 return self.dcx().span_delayed_bug(
730 span,
731 "type outlives claues errored outside borrowck without any other error",
732 );
733 }
734 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..))
735 | ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..)) => {
736 ::rustc_span::macros::bug_impl(Some(span),
format_args!("outlives clauses should not error outside borrowck. obligation: `{0:?}`",
obligation), Location::caller())span_bug!(
737 span,
738 "outlives clauses should not error outside borrowck. obligation: `{:?}`",
739 obligation
740 )
741 }
742
743 ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => {
744 ::rustc_span::macros::bug_impl(Some(span),
format_args!("projection clauses should be implied from elsewhere. obligation: `{0:?}`",
obligation), Location::caller())span_bug!(
745 span,
746 "projection clauses should be implied from elsewhere. obligation: `{:?}`",
747 obligation
748 )
749 }
750
751 ty::PredicateKind::DynCompatible(trait_def_id) => {
752 let violations = self.tcx.dyn_compatibility_violations(trait_def_id);
753 let mut err = report_dyn_incompatibility(
754 self.tcx,
755 span,
756 None,
757 trait_def_id,
758 violations,
759 );
760 if let hir::Node::Item(item) =
761 self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
762 && let hir::ItemKind::Impl(impl_) = item.kind
763 && let None = impl_.of_trait
764 && let hir::TyKind::TraitObject(_, tagged_ptr) = impl_.self_ty.kind
765 && let TraitObjectSyntax::None = tagged_ptr.tag()
766 && impl_.self_ty.span.edition().at_least_rust_2021()
767 {
768 err.downgrade_to_delayed_bug();
771 }
772 err
773 }
774
775 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(ty)) => {
776 let ty = self.deeply_resolve_ignoring_regions(ty);
777 if self.next_trait_solver() {
778 if let Err(guar) = ty.error_reported() {
779 return guar;
780 }
781
782 self.dcx().struct_span_err(
785 span,
786 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the type `{0}` is not well-formed",
ty))
})format!("the type `{ty}` is not well-formed"),
787 )
788 } else {
789 ::rustc_span::macros::bug_impl(Some(span),
format_args!("WF predicate not satisfied for {0:?}", ty),
Location::caller());span_bug!(span, "WF predicate not satisfied for {:?}", ty);
795 }
796 }
797
798 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
803 | ty::PredicateKind::ConstEquate { .. }
804 | ty::PredicateKind::Ambiguous
805 | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature { .. })
806 | ty::PredicateKind::NormalizesTo { .. }
807 | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType { .. })
808 | ty::PredicateKind::Clause(ty::ClauseKind::CompressedTrait(..)) => {
809 ::rustc_span::macros::bug_impl(Some(span),
format_args!("Unexpected `Predicate` for `SelectionError`: `{0:?}`",
obligation), Location::caller())span_bug!(
810 span,
811 "Unexpected `Predicate` for `SelectionError`: `{:?}`",
812 obligation
813 )
814 }
815 }
816 }
817
818 SelectionError::SignatureMismatch(SignatureMismatchData {
819 found_trait_ref,
820 expected_trait_ref,
821 terr: terr @ TypeError::CyclicTy(_),
822 }) => self.report_cyclic_signature_error(
823 &obligation,
824 found_trait_ref,
825 expected_trait_ref,
826 terr,
827 ),
828 SelectionError::SignatureMismatch(SignatureMismatchData {
829 found_trait_ref,
830 expected_trait_ref,
831 terr: _,
832 }) => {
833 match self.report_signature_mismatch_error(
834 &obligation,
835 span,
836 found_trait_ref,
837 expected_trait_ref,
838 ) {
839 Ok(err) => err,
840 Err(guar) => return guar,
841 }
842 }
843
844 SelectionError::TraitDynIncompatible(did) => {
845 let violations = self.tcx.dyn_compatibility_violations(did);
846 report_dyn_incompatibility(self.tcx, span, None, did, violations)
847 }
848
849 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
850 ::rustc_span::macros::bug_impl(None,
format_args!("MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"),
Location::caller())bug!(
851 "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
852 )
853 }
854 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
855 match self.report_not_const_evaluatable_error(&obligation, span) {
856 Ok(err) => err,
857 Err(guar) => return guar,
858 }
859 }
860
861 SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(guar))
863 | SelectionError::Overflow(OverflowError::Error(guar)) => {
864 self.set_tainted_by_errors(guar);
865 return guar;
866 }
867
868 SelectionError::Overflow(_) => {
869 ::rustc_span::macros::bug_impl(None,
format_args!("overflow should be handled before the `report_selection_error` path"),
Location::caller());bug!("overflow should be handled before the `report_selection_error` path");
870 }
871
872 SelectionError::ConstArgHasWrongType { ct, ct_ty, expected_ty } => {
873 let expected_ty_str = self.tcx.short_string(expected_ty, &mut long_ty_file);
874 let ct_str = self.tcx.short_string(ct, &mut long_ty_file);
875 let mut diag_span = span;
876 let mut is_array_len = false;
877 if let ObligationCauseCode::ArrayLen(_, span) = obligation.cause.code() {
878 let mut finder = FindExprBySpan::new(*span, self.tcx);
879 match self.infcx.tcx.hir_node_by_def_id(obligation.cause.body_def_id) {
880 hir::Node::Item(item) => finder.visit_item(item),
881 hir::Node::ImplItem(item) => finder.visit_impl_item(item),
882 hir::Node::TraitItem(item) => finder.visit_trait_item(item),
883 _ => {}
884 }
885 if let Some(arr_ty) = finder.ty_result
886 && let hir::TyKind::Array(_, len) = arr_ty.kind
887 {
888 diag_span = len.span;
889 is_array_len = true;
890 } else if let Some(arr) = finder.result
891 && let hir::ExprKind::Repeat(_, len) = arr.kind
892 {
893 diag_span = len.span;
894 is_array_len = true;
895 }
896 }
897 let mut diag = self.dcx().struct_span_err(
898 diag_span,
899 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the constant `{0}` is not of type `{1}`",
ct_str, expected_ty_str))
})format!("the constant `{ct_str}` is not of type `{expected_ty_str}`"),
900 );
901 diag.long_ty_path = long_ty_file;
902 if let ConstKind::Param(param_const) = ct.kind() {
903 for param in self
904 .tcx
905 .generics_of(obligation.cause.body_def_id.to_def_id())
906 .own_params
907 .iter()
908 {
909 if let GenericParamDefKind::Const { .. } = param.kind
910 && param.index == param_const.index
911 && param.name == param_const.name
912 {
913 let span = self.tcx.def_span(param.def_id);
914 diag.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", param.name))
})format!("`{}` defined here", param.name));
915 }
916 }
917 }
918
919 if is_array_len {
920 let ty = self.tcx.short_string(ct_ty, &mut diag.long_ty_path);
921 diag.span_label(
922 diag_span,
923 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("array length expected `{0}`, found `{1}`",
expected_ty_str, ty))
})format!("array length expected `{expected_ty_str}`, found `{ty}`"),
924 );
925 } else {
926 self.note_type_err(
927 &mut diag,
928 &obligation.cause,
929 None,
930 None,
931 TypeError::Sorts(ty::error::ExpectedFound::new(expected_ty, ct_ty)),
932 false,
933 None,
934 );
935 }
936 diag
937 }
938 };
939
940 self.note_obligation_cause(&mut err, &obligation);
941 self.silence_redundant_cause(&mut err, &obligation, &root_obligation);
942 err.emit_err()
943 }
944}
945
946impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
947 pub(super) fn apply_do_not_recommend(
948 &self,
949 obligation: &mut PredicateObligation<'tcx>,
950 root_obligation: &PredicateObligation<'tcx>,
951 ) -> bool {
952 let mut base_cause = obligation.cause.code().clone();
953 let mut applied_do_not_recommend = false;
954 loop {
955 if let ObligationCauseCode::ImplDerived(ref c) = base_cause {
956 if self.tcx.do_not_recommend_impl(c.impl_or_alias_def_id) {
957 let code = (*c.derived.parent_code).clone();
958 if code == *root_obligation.cause.code()
961 && root_obligation.cause.span.ctxt() == obligation.cause.span.ctxt()
962 && !root_obligation.cause.span.contains(obligation.cause.span)
963 {
964 obligation.cause.span = root_obligation.cause.span;
965 }
966 obligation.cause.map_code(|_| code);
967 obligation.predicate = c.derived.parent_trait_pred.upcast(self.tcx);
968 applied_do_not_recommend = true;
969 }
970 }
971 if let Some(parent_cause) = base_cause.parent() {
972 base_cause = parent_cause.clone();
973 } else {
974 break;
975 }
976 }
977
978 applied_do_not_recommend
979 }
980
981 fn report_host_effect_error(
982 &self,
983 clause: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>,
984 main_obligation: &PredicateObligation<'tcx>,
985 span: Span,
986 ) -> Diag<'a> {
987 let trait_ref = clause.map_bound(|clause| ty::TraitClause {
991 trait_ref: clause.trait_ref,
992 polarity: ty::ClausePolarity::Positive,
993 });
994 let mut file = None;
995
996 let err_msg = self.get_standard_error_message(
997 trait_ref,
998 Some(clause.constness()),
999 String::new(),
1000 &mut file,
1001 );
1002 let mut diag = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", err_msg))
})).with_code(E0277)
}struct_span_code_err!(self.dcx(), span, E0277, "{}", err_msg);
1003 *diag.long_ty_path() = file;
1004 let obligation = Obligation::new(
1005 self.tcx,
1006 ObligationCause::dummy(),
1007 main_obligation.param_env,
1008 trait_ref,
1009 );
1010 if !self.predicate_may_hold(&obligation) {
1011 diag.downgrade_to_delayed_bug();
1012 }
1013
1014 if let Ok(Some(ImplSource::UserDefined(impl_data))) =
1015 SelectionContext::new(self).poly_select(&obligation.with(self.tcx, trait_ref))
1016 {
1017 let impl_did = impl_data.impl_def_id;
1018 let trait_did = trait_ref.def_id();
1019 let impl_span = self.tcx.def_span(impl_did);
1020 let trait_name = self.tcx.item_name(trait_did);
1021
1022 if self.tcx.is_const_trait(trait_did) && !self.tcx.is_const_trait_impl(impl_did) {
1023 if !impl_did.is_local() {
1024 diag.span_note(
1025 impl_span,
1026 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("trait `{0}` is implemented but not `const`",
trait_name))
})format!("trait `{trait_name}` is implemented but not `const`"),
1027 );
1028 }
1029
1030 if let Some(command) =
1031 {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(impl_did, &self.tcx)
{
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(OnConst { directive, ..
}) => {
break 'done Some(directive.as_deref());
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.tcx, impl_did, OnConst {directive, ..} => directive.as_deref())
1032 .flatten()
1033 {
1034 let (_, mut format_args) = self.on_unimplemented_components(
1035 trait_ref,
1036 main_obligation,
1037 diag.long_ty_path(),
1038 false,
1039 );
1040 if let ty::Adt(def, args) = trait_ref.self_ty().skip_binder().kind() {
1041 for param in self.tcx.generics_of(def.did()).own_params.iter() {
1042 match param.kind {
1043 GenericParamDefKind::Type { .. }
1044 | GenericParamDefKind::Const { .. } => {
1045 format_args
1046 .generic_args
1047 .push((param.name, args[param.index as usize].to_string()));
1048 }
1049 _ => continue,
1050 }
1051 }
1052 }
1053 let CustomDiagnostic { message, label, notes, parent_label: _ } =
1054 command.eval(None, &format_args);
1055
1056 if let Some(message) = message {
1057 diag.primary_message(message);
1058 }
1059 if let Some(label) = label {
1060 diag.span_label(span, label);
1061 }
1062 for note in notes {
1063 diag.note(note);
1064 }
1065 } else if let Some(impl_did) = impl_did.as_local()
1066 && let item = self.tcx.hir_expect_item(impl_did)
1067 && let hir::ItemKind::Impl(impl_) = item.kind
1068 && impl_.of_trait.is_some()
1069 {
1070 diag.span_suggestion_verbose(
1072 item.span.shrink_to_lo(),
1073 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("make the `impl` of trait `{0}` `const`",
trait_name))
})format!("make the `impl` of trait `{trait_name}` `const`"),
1074 "const ".to_string(),
1075 Applicability::MaybeIncorrect,
1076 );
1077 }
1078 }
1079 } else if let ty::Param(param) = trait_ref.self_ty().skip_binder().kind()
1080 && let Some(generics) =
1081 self.tcx.hir_node_by_def_id(main_obligation.cause.body_def_id).generics()
1082 {
1083 let constraint = {
let _guard = NoTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[const] {0}",
trait_ref.map_bound(|tr|
tr.trait_ref).print_trait_sugared()))
})
}ty::print::with_no_trimmed_paths!(format!(
1084 "[const] {}",
1085 trait_ref.map_bound(|tr| tr.trait_ref).print_trait_sugared(),
1086 ));
1087 ty::suggest_constraining_type_param(
1088 self.tcx,
1089 generics,
1090 &mut diag,
1091 param.name.as_str(),
1092 &constraint,
1093 Some(trait_ref.def_id()),
1094 None,
1095 );
1096 }
1097 diag
1098 }
1099
1100 fn emit_specialized_closure_kind_error(
1101 &self,
1102 obligation: &PredicateObligation<'tcx>,
1103 mut trait_pred: ty::PolyTraitClause<'tcx>,
1104 ) -> Option<ErrorGuaranteed> {
1105 if self.tcx.is_lang_item(trait_pred.def_id(), LangItem::AsyncFnKindHelper) {
1108 let mut code = obligation.cause.code();
1109 if let ObligationCauseCode::FunctionArg { parent_code, .. } = code {
1111 code = &**parent_code;
1112 }
1113 if let Some((_, Some(parent))) = code.parent_with_predicate() {
1115 trait_pred = parent;
1116 }
1117 }
1118
1119 let original_self_ty = trait_pred.self_ty().skip_binder();
1120 let peeled_self_ty = original_self_ty.peel_refs();
1121
1122 let is_ref_to_closure = #[allow(non_exhaustive_omitted_patterns)] match original_self_ty.kind() {
ty::Ref(..) => true,
_ => false,
}matches!(original_self_ty.kind(), ty::Ref(..))
1123 && #[allow(non_exhaustive_omitted_patterns)] match peeled_self_ty.kind() {
ty::Closure(..) => true,
_ => false,
}matches!(peeled_self_ty.kind(), ty::Closure(..));
1124
1125 let self_ty = if is_ref_to_closure { peeled_self_ty } else { original_self_ty };
1126
1127 let (asyncness, expected_kind) =
1128 self.tcx.maybe_async_fn_trait_kind_from_def_id(trait_pred.def_id())?;
1129
1130 let trait_prefix = asyncness.as_trait_prefix_str();
1131
1132 let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() {
1133 ty::Closure(def_id, args) => {
1134 (def_id, args.as_closure().sig().map_bound(|sig| sig.inputs()[0]), false)
1135 }
1136 ty::CoroutineClosure(def_id, args) => (
1137 def_id,
1138 args.as_coroutine_closure()
1139 .coroutine_closure_sig()
1140 .map_bound(|sig| sig.tupled_inputs_ty),
1141 !args.as_coroutine_closure().tupled_upvars_ty().is_ty_var()
1142 && args.as_coroutine_closure().has_self_borrows(),
1143 ),
1144 _ => return None,
1145 };
1146
1147 let expected_args = trait_pred.map_bound(|trait_pred| trait_pred.trait_ref.args.type_at(1));
1148
1149 if self.enter_forall(found_args, |found_args| {
1152 self.enter_forall(expected_args, |expected_args| {
1153 !self.can_eq(obligation.param_env, expected_args, found_args)
1154 })
1155 }) {
1156 return None;
1157 }
1158
1159 let mut found_kind = self.closure_kind(self_ty);
1160 let mut kind_origin = None;
1161
1162 if found_kind.is_none()
1163 && is_ref_to_closure
1164 && !asyncness.is_async()
1165 && let Some(local_def_id) = closure_def_id.as_local()
1166 && let Some((inferred_kind, origin)) = (self.infer_closure_kind)(local_def_id)
1167 {
1168 found_kind = Some(inferred_kind);
1169 kind_origin = origin;
1170 }
1171
1172 let (_, root_trait_pred) = obligation.cause.code().peel_derives_with_predicate();
1173 let root_expected = root_trait_pred
1174 .and_then(|pred| self.tcx.maybe_async_fn_trait_kind_from_def_id(pred.def_id()));
1175
1176 if let ty::ClosureKind::Fn | ty::ClosureKind::FnMut = expected_kind
1179 && let Some(ty::ClosureKind::FnOnce) = found_kind
1180 && let Some((root_asyncness, ty::ClosureKind::FnOnce)) = root_expected
1181 && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1182 && let arg = self.tcx.hir_expect_expr(*arg_hir_id)
1183 && asyncness == root_asyncness
1184 {
1185 let mut err = self.report_ref_to_fn_once_error(
1186 closure_def_id,
1187 trait_prefix,
1188 kind_origin,
1189 arg.span,
1190 );
1191
1192 self.suggest_remove_ref_for_closure(&mut err, obligation);
1193 self.note_obligation_cause(&mut err, obligation);
1194 return Some(err.emit_err());
1195 }
1196
1197 if let Some(found_kind) = found_kind
1198 && !found_kind.extends(expected_kind)
1199 {
1200 let mut err = self.report_closure_error(
1201 &obligation,
1202 closure_def_id,
1203 found_kind,
1204 expected_kind,
1205 trait_prefix,
1206 kind_origin,
1207 );
1208
1209 self.suggest_change_mut_ref_for_closure(&mut err, obligation);
1210 self.note_obligation_cause(&mut err, &obligation);
1211 return Some(err.emit_err());
1212 }
1213
1214 if has_self_borrows && expected_kind != ty::ClosureKind::FnOnce {
1218 let coro_kind = match self
1219 .tcx
1220 .coroutine_kind(self.tcx.coroutine_for_closure(closure_def_id))
1221 .unwrap()
1222 {
1223 rustc_hir::CoroutineKind::Desugared(desugaring, _) => desugaring.to_string(),
1224 coro => coro.to_string(),
1225 };
1226 let mut err = self.dcx().create_err(CoroClosureNotFn {
1227 span: self.tcx.def_span(closure_def_id),
1228 kind: expected_kind.as_str(),
1229 coro_kind,
1230 });
1231 self.note_obligation_cause(&mut err, &obligation);
1232 return Some(err.emit_err());
1233 }
1234
1235 None
1236 }
1237
1238 fn fn_arg_obligation(
1239 &self,
1240 obligation: &PredicateObligation<'tcx>,
1241 ) -> Result<(), ErrorGuaranteed> {
1242 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1243 && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
1244 && let arg = arg.peel_borrows()
1245 && let hir::ExprKind::Path(hir::QPath::Resolved(
1246 None,
1247 hir::Path { res: hir::def::Res::Local(hir_id), .. },
1248 )) = arg.kind
1249 && let Node::Pat(pat) = self.tcx.hir_node(*hir_id)
1250 && let Some((preds, guar)) = self.reported_trait_errors.borrow().get(&pat.span)
1251 && preds.contains(&obligation.as_goal())
1252 {
1253 return Err(*guar);
1254 }
1255 Ok(())
1256 }
1257
1258 fn detect_negative_literal(
1259 &self,
1260 obligation: &PredicateObligation<'tcx>,
1261 trait_pred: ty::PolyTraitClause<'tcx>,
1262 err: &mut Diag<'_>,
1263 ) -> bool {
1264 if let ObligationCauseCode::UnOp { hir_id, .. } = obligation.cause.code()
1265 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1266 && let hir::ExprKind::Unary(hir::UnOp::Neg, inner) = expr.kind
1267 && let hir::ExprKind::Lit(lit) = inner.kind
1268 && let LitKind::Int(_, LitIntType::Unsuffixed) = lit.node
1269 {
1270 err.span_suggestion_verbose(
1271 lit.span.shrink_to_hi(),
1272 "consider specifying an integer type that can be negative",
1273 match trait_pred.skip_binder().self_ty().kind() {
1274 ty::Uint(ty::UintTy::Usize) => "isize",
1275 ty::Uint(ty::UintTy::U8) => "i8",
1276 ty::Uint(ty::UintTy::U16) => "i16",
1277 ty::Uint(ty::UintTy::U32) => "i32",
1278 ty::Uint(ty::UintTy::U64) => "i64",
1279 ty::Uint(ty::UintTy::U128) => "i128",
1280 _ => "i64",
1281 }
1282 .to_string(),
1283 Applicability::MaybeIncorrect,
1284 );
1285 return true;
1286 }
1287 false
1288 }
1289
1290 fn try_conversion_context(
1294 &self,
1295 obligation: &PredicateObligation<'tcx>,
1296 trait_pred: ty::PolyTraitClause<'tcx>,
1297 err: &mut Diag<'_>,
1298 ) -> (bool, bool) {
1299 let span = obligation.cause.span;
1300 struct FindMethodSubexprOfTry {
1302 search_span: Span,
1303 }
1304 impl<'v> Visitor<'v> for FindMethodSubexprOfTry {
1305 type Result = ControlFlow<&'v hir::Expr<'v>>;
1306 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
1307 if let hir::ExprKind::Match(expr, _arms, hir::MatchSource::TryDesugar(_)) = ex.kind
1308 && ex.span.with_lo(ex.span.hi() - BytePos(1)).lo_hi()
1309 == self.search_span.lo_hi()
1310 && let hir::ExprKind::Call(_, [expr, ..]) = expr.kind
1311 {
1312 ControlFlow::Break(expr)
1313 } else {
1314 hir::intravisit::walk_expr(self, ex)
1315 }
1316 }
1317 }
1318 let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_def_id);
1319 let Some(body_id) = self.tcx.hir_node(hir_id).body_id() else { return (false, false) };
1320 let ControlFlow::Break(expr) =
1321 (FindMethodSubexprOfTry { search_span: span }).visit_body(self.tcx.hir_body(body_id))
1322 else {
1323 return (false, false);
1324 };
1325 let Some(typeck) = &self.typeck_results else {
1326 return (false, false);
1327 };
1328 let ObligationCauseCode::QuestionMark = obligation.cause.code().peel_derives() else {
1329 return (false, false);
1330 };
1331 let self_ty = trait_pred.skip_binder().self_ty();
1332 let found_ty = trait_pred.skip_binder().trait_ref.args.get(1).and_then(|a| a.as_type());
1333 let noted_missing_impl =
1334 self.note_missing_impl_for_question_mark(err, self_ty, found_ty, trait_pred);
1335
1336 let mut prev_ty = self.deeply_resolve_ignoring_regions(
1337 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1338 );
1339
1340 let get_e_type = |prev_ty: Ty<'tcx>| -> Option<Ty<'tcx>> {
1344 let ty::Adt(def, args) = prev_ty.kind() else {
1345 return None;
1346 };
1347 let Some(arg) = args.get(1) else {
1348 return None;
1349 };
1350 if !self.tcx.is_diagnostic_item(sym::Result, def.did()) {
1351 return None;
1352 }
1353 arg.as_type()
1354 };
1355
1356 let mut suggested = false;
1357 let mut chain = ::alloc::vec::Vec::new()vec![];
1358
1359 let mut expr = expr;
1361 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
1362 expr = rcvr_expr;
1366 chain.push((span, prev_ty));
1367
1368 let next_ty = self.deeply_resolve_ignoring_regions(
1369 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1370 );
1371
1372 let is_diagnostic_item = |symbol: Symbol, ty: Ty<'tcx>| {
1373 let ty::Adt(def, _) = ty.kind() else {
1374 return false;
1375 };
1376 self.tcx.is_diagnostic_item(symbol, def.did())
1377 };
1378 if let Some(ty) = get_e_type(prev_ty)
1382 && let Some(found_ty) = found_ty
1383 && (
1388 ( path_segment.ident.name == sym::map_err
1390 && is_diagnostic_item(sym::Result, next_ty)
1391 ) || ( path_segment.ident.name == sym::ok_or_else
1393 && is_diagnostic_item(sym::Option, next_ty)
1394 )
1395 )
1396 && let ty::Tuple(tys) = found_ty.kind()
1398 && tys.is_empty()
1399 && self.can_eq(obligation.param_env, ty, found_ty)
1401 && let [arg] = args
1403 && let hir::ExprKind::Closure(closure) = arg.kind
1404 && let body = self.tcx.hir_body(closure.body)
1406 && let hir::ExprKind::Block(block, _) = body.value.kind
1407 && let None = block.expr
1408 && let [.., stmt] = block.stmts
1410 && let hir::StmtKind::Semi(expr) = stmt.kind
1411 && let expr_ty = self.deeply_resolve_ignoring_regions(
1412 typeck.expr_ty_adjusted_opt(expr)
1413 .unwrap_or(Ty::new_misc_error(self.tcx)),
1414 )
1415 && self
1416 .infcx
1417 .type_implements_trait(
1418 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1419 [self_ty, expr_ty],
1420 obligation.param_env,
1421 )
1422 .must_apply_modulo_regions()
1423 {
1424 suggested = true;
1425 err.span_suggestion_short(
1426 stmt.span.with_lo(expr.span.hi()),
1427 "remove this semicolon",
1428 String::new(),
1429 Applicability::MachineApplicable,
1430 );
1431 }
1432
1433 prev_ty = next_ty;
1434
1435 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1436 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
1437 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
1438 {
1439 let parent = self.tcx.parent_hir_node(binding.hir_id);
1440 if let hir::Node::LetStmt(local) = parent
1442 && let Some(binding_expr) = local.init
1443 {
1444 expr = binding_expr;
1446 }
1447 if let hir::Node::Param(_param) = parent {
1448 break;
1450 }
1451 }
1452 }
1453 prev_ty = self.deeply_resolve_ignoring_regions(
1457 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1458 );
1459 chain.push((expr.span, prev_ty));
1460
1461 let mut prev = None;
1462 let mut iter = chain.into_iter().rev().peekable();
1463 while let Some((span, err_ty)) = iter.next() {
1464 let is_last = iter.peek().is_none();
1465 let err_ty = get_e_type(err_ty);
1466 let err_ty = match (err_ty, prev) {
1467 (Some(err_ty), Some(prev)) if !self.can_eq(obligation.param_env, err_ty, prev) => {
1468 err_ty
1469 }
1470 (Some(err_ty), None) => err_ty,
1471 _ => {
1472 prev = err_ty;
1473 continue;
1474 }
1475 };
1476
1477 let implements_from = self
1478 .infcx
1479 .type_implements_trait(
1480 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1481 [self_ty, err_ty],
1482 obligation.param_env,
1483 )
1484 .must_apply_modulo_regions();
1485
1486 let err_ty_str = self.tcx.short_string(err_ty, err.long_ty_path());
1487 let label = if !implements_from && is_last {
1488 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this can\'t be annotated with `?` because it has type `Result<_, {0}>`",
err_ty_str))
})format!(
1489 "this can't be annotated with `?` because it has type `Result<_, {err_ty_str}>`"
1490 )
1491 } else {
1492 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this has type `Result<_, {0}>`",
err_ty_str))
})format!("this has type `Result<_, {err_ty_str}>`")
1493 };
1494
1495 if !suggested || !implements_from {
1496 err.span_label(span, label);
1497 }
1498 prev = Some(err_ty);
1499 }
1500 (suggested, noted_missing_impl)
1501 }
1502
1503 fn note_missing_impl_for_question_mark(
1504 &self,
1505 err: &mut Diag<'_>,
1506 self_ty: Ty<'_>,
1507 found_ty: Option<Ty<'_>>,
1508 trait_pred: ty::PolyTraitClause<'tcx>,
1509 ) -> bool {
1510 match (self_ty.kind(), found_ty) {
1511 (ty::Adt(def, _), Some(ty))
1512 if let ty::Adt(found, _) = ty.kind()
1513 && def.did().is_local()
1514 && found.did().is_local() =>
1515 {
1516 err.span_note(
1517 self.tcx.def_span(def.did()),
1518 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` needs to implement `From<{1}>`",
self_ty, ty))
})format!("`{self_ty}` needs to implement `From<{ty}>`"),
1519 );
1520 }
1521 (ty::Adt(def, _), None) if def.did().is_local() => {
1522 let trait_path = self.tcx.short_string(
1523 trait_pred.skip_binder().trait_ref.print_only_trait_path(),
1524 err.long_ty_path(),
1525 );
1526 err.span_note(
1527 self.tcx.def_span(def.did()),
1528 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` needs to implement `{1}`",
self_ty, trait_path))
})format!("`{self_ty}` needs to implement `{trait_path}`"),
1529 );
1530 }
1531 (ty::Adt(def, _), Some(ty)) if def.did().is_local() => {
1532 err.span_note(
1533 self.tcx.def_span(def.did()),
1534 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` needs to implement `From<{1}>`",
self_ty, ty))
})format!("`{self_ty}` needs to implement `From<{ty}>`"),
1535 );
1536 }
1537 (_, Some(ty))
1538 if let ty::Adt(def, _) = ty.kind()
1539 && def.did().is_local() =>
1540 {
1541 err.span_note(
1542 self.tcx.def_span(def.did()),
1543 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` needs to implement `Into<{1}>`",
ty, self_ty))
})format!("`{ty}` needs to implement `Into<{self_ty}>`"),
1544 );
1545 }
1546 _ => return false,
1547 }
1548 true
1549 }
1550
1551 fn report_const_param_ty_error(
1552 &self,
1553 ty: Ty<'tcx>,
1554 span: Span,
1555 obligation: &PredicateObligation<'tcx>,
1556 ) -> Diag<'a> {
1557 let mut file = None;
1558 let ty_str = self.tcx.short_string(ty, &mut file);
1559 let mut diag = match ty.kind() {
1560 ty::Float(_) => {
1561 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is forbidden as the type of a const generic parameter",
ty_str))
})).with_code(E0741)
}struct_span_code_err!(
1562 self.dcx(),
1563 span,
1564 E0741,
1565 "`{ty_str}` is forbidden as the type of a const generic parameter",
1566 )
1567 }
1568 ty::FnPtr(..) => {
1569 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("using function pointers as const generic parameters is forbidden"))
})).with_code(E0741)
}struct_span_code_err!(
1570 self.dcx(),
1571 span,
1572 E0741,
1573 "using function pointers as const generic parameters is forbidden",
1574 )
1575 }
1576 ty::RawPtr(_, _) => {
1577 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("using raw pointers as const generic parameters is forbidden"))
})).with_code(E0741)
}struct_span_code_err!(
1578 self.dcx(),
1579 span,
1580 E0741,
1581 "using raw pointers as const generic parameters is forbidden",
1582 )
1583 }
1584 ty::Adt(def, _) => {
1585 let mut diag = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
ty_str))
})).with_code(E0741)
}struct_span_code_err!(
1587 self.dcx(),
1588 span,
1589 E0741,
1590 "`{ty_str}` must implement `ConstParamTy` to be used as the type of a const \
1591 generic parameter",
1592 );
1593 if let Some(span) = self.tcx.hir_span_if_local(def.did())
1596 && obligation.cause.code().parent().is_none()
1597 {
1598 if ty.is_structural_eq_shallow(self.tcx) {
1599 diag.span_suggestion_verbose(
1600 span.shrink_to_lo(),
1601 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy)]` to the {0}",
def.descr()))
})format!("add `#[derive(ConstParamTy)]` to the {}", def.descr()),
1602 "#[derive(ConstParamTy)]\n",
1603 Applicability::MachineApplicable,
1604 );
1605 } else {
1606 diag.span_suggestion_verbose(
1609 span.shrink_to_lo(),
1610 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {0}",
def.descr()))
})format!(
1611 "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {}",
1612 def.descr()
1613 ),
1614 "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1615 Applicability::MachineApplicable,
1616 );
1617 }
1618 }
1619 diag
1620 }
1621 _ => {
1622 {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` can\'t be used as a const parameter type",
ty_str))
})).with_code(E0741)
}struct_span_code_err!(
1623 self.dcx(),
1624 span,
1625 E0741,
1626 "`{ty_str}` can't be used as a const parameter type",
1627 )
1628 }
1629 };
1630 diag.long_ty_path = file;
1631
1632 let mut code = obligation.cause.code();
1633 let mut pred = obligation.predicate.as_trait_clause();
1634 while let Some((next_code, next_pred)) = code.parent_with_predicate() {
1635 if let Some(pred) = pred {
1636 self.enter_forall(pred, |pred| {
1637 let ty = self.tcx.short_string(pred.self_ty(), diag.long_ty_path());
1638 let trait_path = self
1639 .tcx
1640 .short_string(pred.print_modifiers_and_trait_path(), diag.long_ty_path());
1641 diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` must implement `{1}`, but it does not",
ty, trait_path))
})format!("`{ty}` must implement `{trait_path}`, but it does not"));
1642 })
1643 }
1644 code = next_code;
1645 pred = next_pred;
1646 }
1647
1648 diag
1649 }
1650}
1651
1652impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
1653 fn can_match_trait(
1654 &self,
1655 param_env: ty::ParamEnv<'tcx>,
1656 goal: ty::TraitClause<'tcx>,
1657 assumption: ty::PolyTraitClause<'tcx>,
1658 ) -> bool {
1659 if goal.polarity != assumption.polarity() {
1661 return false;
1662 }
1663
1664 let trait_assumption = self.instantiate_binder_with_fresh_vars(
1665 DUMMY_SP,
1666 infer::BoundRegionConversionTime::HigherRankedType,
1667 assumption,
1668 );
1669
1670 self.can_eq(param_env, goal.trait_ref, trait_assumption.trait_ref)
1671 }
1672
1673 fn can_match_host_effect(
1674 &self,
1675 param_env: ty::ParamEnv<'tcx>,
1676 goal: ty::HostEffectClause<'tcx>,
1677 assumption: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>,
1678 ) -> bool {
1679 let assumption = self.instantiate_binder_with_fresh_vars(
1680 DUMMY_SP,
1681 infer::BoundRegionConversionTime::HigherRankedType,
1682 assumption,
1683 );
1684
1685 assumption.constness.satisfies(goal.constness)
1686 && self.can_eq(param_env, goal.trait_ref, assumption.trait_ref)
1687 }
1688
1689 fn as_host_effect_clause(
1690 predicate: ty::Predicate<'tcx>,
1691 ) -> Option<ty::Binder<'tcx, ty::HostEffectClause<'tcx>>> {
1692 predicate.as_clause().and_then(|clause| match clause.kind().skip_binder() {
1693 ty::ClauseKind::HostEffect(host_clause) => Some(clause.kind().rebind(host_clause)),
1694 _ => None,
1695 })
1696 }
1697
1698 fn can_match_projection(
1699 &self,
1700 param_env: ty::ParamEnv<'tcx>,
1701 goal: ty::ProjectionClause<'tcx>,
1702 assumption: ty::PolyProjectionClause<'tcx>,
1703 ) -> bool {
1704 let assumption = self.instantiate_binder_with_fresh_vars(
1705 DUMMY_SP,
1706 infer::BoundRegionConversionTime::HigherRankedType,
1707 assumption,
1708 );
1709
1710 self.can_eq(param_env, goal.projection_term, assumption.projection_term)
1711 && self.can_eq(param_env, goal.term, assumption.term)
1712 }
1713
1714 {}
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() || { false }
{
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("error_implies",
"rustc_trait_selection::error_reporting::traits::fulfillment_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
::tracing_core::__macro_support::Option::Some(1716u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::fulfillment_errors"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cond")
}> =
::tracing::__macro_support::FieldName::new("cond");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("error")
}> =
::tracing::__macro_support::FieldName::new("error");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cond)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&error)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy
:: needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: bool = loop {};
return __tracing_attr_fake_return;
}
{
if cond == error { return true; }
if cond.param_env != error.param_env { return false; }
let param_env = error.param_env;
if let Some(error) = error.predicate.as_trait_clause() {
self.enter_forall(error,
|error|
{
elaborate(self.tcx,
std::iter::once(cond.predicate)).filter_map(|implied|
implied.as_trait_clause()).any(|implied|
self.can_match_trait(param_env, error, implied))
})
} else if let Some(error) =
Self::as_host_effect_clause(error.predicate) {
self.enter_forall(error,
|error|
{
elaborate(self.tcx,
std::iter::once(cond.predicate)).filter_map(Self::as_host_effect_clause).any(|implied|
self.can_match_host_effect(param_env, error, implied))
})
} else if let Some(error) =
error.predicate.as_projection_clause() {
self.enter_forall(error,
|error|
{
elaborate(self.tcx,
std::iter::once(cond.predicate)).filter_map(|implied|
implied.as_projection_clause()).any(|implied|
self.can_match_projection(param_env, error, implied))
})
} else { false }
}
})();
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs:1716",
"rustc_trait_selection::error_reporting::traits::fulfillment_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
::tracing_core::__macro_support::Option::Some(1716u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::fulfillment_errors"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(self), ret)]
1717 pub(super) fn error_implies(
1718 &self,
1719 cond: Goal<'tcx, ty::Predicate<'tcx>>,
1720 error: Goal<'tcx, ty::Predicate<'tcx>>,
1721 ) -> bool {
1722 if cond == error {
1723 return true;
1724 }
1725
1726 if cond.param_env != error.param_env {
1730 return false;
1731 }
1732 let param_env = error.param_env;
1733
1734 if let Some(error) = error.predicate.as_trait_clause() {
1735 self.enter_forall(error, |error| {
1736 elaborate(self.tcx, std::iter::once(cond.predicate))
1737 .filter_map(|implied| implied.as_trait_clause())
1738 .any(|implied| self.can_match_trait(param_env, error, implied))
1739 })
1740 } else if let Some(error) = Self::as_host_effect_clause(error.predicate) {
1741 self.enter_forall(error, |error| {
1742 elaborate(self.tcx, std::iter::once(cond.predicate))
1743 .filter_map(Self::as_host_effect_clause)
1744 .any(|implied| self.can_match_host_effect(param_env, error, implied))
1745 })
1746 } else if let Some(error) = error.predicate.as_projection_clause() {
1747 self.enter_forall(error, |error| {
1748 elaborate(self.tcx, std::iter::once(cond.predicate))
1749 .filter_map(|implied| implied.as_projection_clause())
1750 .any(|implied| self.can_match_projection(param_env, error, implied))
1751 })
1752 } else {
1753 false
1754 }
1755 }
1756
1757 pub(super) fn trait_error_implies_projection_error(
1761 &self,
1762 cond: Goal<'tcx, ty::Predicate<'tcx>>,
1763 error: Goal<'tcx, ty::Predicate<'tcx>>,
1764 ) -> bool {
1765 if cond.param_env != error.param_env {
1766 return false;
1767 }
1768 let Some(error) = error.predicate.as_projection_clause() else {
1769 return false;
1770 };
1771
1772 self.enter_forall(error, |error| {
1773 if !error.projection_term.kind.is_trait_projection() {
1774 return false;
1775 }
1776 let trait_pred = ty::TraitClause {
1777 trait_ref: error.projection_term.trait_ref(self.tcx),
1778 polarity: ty::ClausePolarity::Positive,
1779 };
1780 elaborate(self.tcx, std::iter::once(cond.predicate))
1785 .filter_map(|implied| implied.as_trait_clause())
1786 .any(|implied| self.can_match_trait(cond.param_env, trait_pred, implied))
1787 && !self.predicate_must_hold_modulo_regions(&Obligation::new(
1788 self.tcx,
1789 ObligationCause::dummy(),
1790 cond.param_env,
1791 trait_pred,
1792 ))
1793 })
1794 }
1795
1796 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("report_projection_error",
"rustc_trait_selection::error_reporting::traits::fulfillment_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
::tracing_core::__macro_support::Option::Some(1796u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::traits::fulfillment_errors"),
::tracing_core::field::FieldSet::new(&[],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{ meta.fields().value_set_all(&[]) })
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: ErrorGuaranteed = loop {};
return __tracing_attr_fake_return;
}
{
let predicate =
self.deeply_resolve_ignoring_regions(obligation.predicate);
if let Err(e) = predicate.error_reported() { return e; }
self.probe(|_|
{
let bound_predicate = predicate.kind();
let (values, err) =
match bound_predicate.skip_binder() {
ty::PredicateKind::Clause(ty::ClauseKind::Projection(data))
=> {
let ocx = ObligationCtxt::new(self);
let data =
self.instantiate_binder_with_fresh_vars(obligation.cause.span,
infer::BoundRegionConversionTime::HigherRankedType,
bound_predicate.rebind(data));
let unnormalized_term =
data.projection_term.to_term(self.tcx, ty::IsRigid::No);
let normalized_term =
ocx.normalize(&obligation.cause, obligation.param_env,
Unnormalized::new_wip(unnormalized_term));
let _ = ocx.try_evaluate_obligations();
if let Err(new_err) =
ocx.eq(&obligation.cause, obligation.param_env, data.term,
normalized_term) {
(Some((data.projection_term,
self.deeply_resolve_ignoring_regions(normalized_term),
data.term)), new_err)
} else { (None, error.err) }
}
_ => (None, error.err),
};
let mut file = None;
let (msg, mut span, mut closure_span) =
values.and_then(|(predicate, normalized_term,
expected_term)|
{
self.maybe_detailed_projection_msg(obligation.cause.span,
predicate, normalized_term, expected_term, &mut file)
}).unwrap_or_else(||
{
({
let _guard = ForceTrimmedGuard::new();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type mismatch resolving `{0}`",
self.tcx.short_string(self.deeply_resolve_ignoring_regions(predicate),
&mut file)))
})
}, obligation.cause.span, None)
});
if closure_span.is_none() &&
let ObligationCauseCode::FunctionArg { arg_hir_id, .. } =
obligation.cause.code() &&
let Node::Expr(arg_expr) = self.tcx.hir_node(*arg_hir_id) &&
let hir::ExprKind::Closure(closure) = arg_expr.kind &&
closure.kind == hir::ClosureKind::Closure {
let body = self.tcx.hir_body(closure.body);
let ret_span =
match body.value.kind {
hir::ExprKind::Block(hir::Block { expr: Some(expr), .. }, _)
=> expr.span,
hir::ExprKind::Block(hir::Block {
expr: None, stmts: [.., last], .. }, _) => {
last.span
}
_ => body.value.span,
};
if !closure.fn_decl_span.overlaps(ret_span) {
closure_span = Some(closure.fn_decl_span);
span = ret_span;
}
}
let mut diag =
{
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", msg))
})).with_code(E0271)
};
*diag.long_ty_path() = file;
let mut mention_bounds = true;
if let Some(span) = closure_span {
if let Some((_, _, expected_ty)) = values &&
let Some(expected_ty) = expected_ty.as_type() &&
let ty::Closure(def_id, _) = expected_ty.kind() &&
self.tcx.def_span(*def_id).overlaps(span) &&
let ObligationCauseCode::FunctionArg {
parent_code, arg_hir_id, .. } = obligation.cause.code() &&
let ObligationCauseCode::WhereClauseInExpr(def_id, span, _,
_) | ObligationCauseCode::WhereClause(def_id, span) =
&**parent_code {
let mut multispan: MultiSpan = (*span).into();
multispan.push_span_label(*span,
"this requires the closure to return itself");
if let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) {
multispan.push_span_label(arg.span,
"this closure would have to return itself");
}
let in_the_item =
match self.tcx.opt_item_name(*def_id) {
Some(name) =>
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in `{0}`", name))
}),
None => String::new(),
};
diag.span_note(multispan,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a bound {0} requires that a closure return itself, which is not possible",
in_the_item))
}));
mention_bounds = false;
} else {
diag.span_label(span, "this closure");
if !span.overlaps(obligation.cause.span) {
diag.span_label(obligation.cause.span, "closure used here");
}
}
}
let secondary_span =
self.probe(|_|
{
let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
predicate.kind().skip_binder() else { return None; };
if !proj.projection_term.kind.is_trait_projection() {
return None;
}
let trait_ref =
self.enter_forall_and_leak_universe(predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)));
let Ok(Some(ImplSource::UserDefined(impl_data))) =
SelectionContext::new(self).select(&obligation.with(self.tcx,
trait_ref)) else { return None; };
let Ok(node) =
specialization_graph::assoc_def(self.tcx,
impl_data.impl_def_id, proj.def_id()) else { return None; };
if !node.is_final() { return None; }
match self.tcx.hir_get_if_local(node.item.def_id) {
Some(hir::Node::TraitItem(hir::TraitItem {
kind: hir::TraitItemKind::Type(_, Some(ty)), .. }) |
hir::Node::ImplItem(hir::ImplItem {
kind: hir::ImplItemKind::Type(ty), .. })) =>
Some((ty.span.into(),
{
let _guard = ForceTrimmedGuard::new();
Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type mismatch resolving `{0}`",
self.tcx.short_string(self.deeply_resolve_ignoring_regions(predicate),
diag.long_ty_path())))
}))
}, true)),
_ => None,
}
});
if let ObligationCauseCode::ReturnType =
obligation.cause.code() {
let body =
self.tcx.hir_body_owned_by(obligation.cause.body_def_id);
let mut visitor = ReturnsVisitor::default();
visitor.visit_body(&body);
if visitor.returns.is_empty() &&
let hir::ExprKind::Block(block, _) = body.value.kind {
let span =
match block.stmts {
[] => body.value.span,
[.., stmt] => stmt.span,
};
if let Some(clause) = predicate.as_clause() &&
let ty::ClauseKind::Projection(projection) =
clause.kind().skip_binder() &&
let Some(ty) = projection.term.as_type() &&
ty == self.tcx.types.unit {
diag.span_label(span, "`()` returned here");
}
} else if let Some(typeck) = &self.typeck_results {
for expr in visitor.returns {
let span =
match expr.kind {
hir::ExprKind::Closure(closure) => closure.fn_decl_span,
_ => expr.span,
};
let msg =
match typeck.expr_ty_adjusted_opt(expr) {
Some(ty) => {
let ty = self.tcx.short_string(ty, diag.long_ty_path());
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` returned here",
ty))
})
}
None => "value returned here".to_string(),
};
diag.span_label(span, msg);
self.point_at_chain_in_return_position(obligation.cause.body_def_id,
expr, typeck, obligation.param_env, &mut diag);
}
}
}
self.note_type_err(&mut diag, &obligation.cause,
secondary_span,
values.map(|(_, normalized_ty, expected_ty)|
{
obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(expected_ty,
normalized_ty)))
}), err, false, Some(span));
if mention_bounds {
self.note_obligation_cause(&mut diag, obligation);
}
diag.emit_err()
})
}
}
}#[instrument(level = "debug", skip_all)]
1797 pub(super) fn report_projection_error(
1798 &self,
1799 obligation: &PredicateObligation<'tcx>,
1800 error: &MismatchedProjectionTypes<'tcx>,
1801 ) -> ErrorGuaranteed {
1802 let predicate = self.deeply_resolve_ignoring_regions(obligation.predicate);
1803
1804 if let Err(e) = predicate.error_reported() {
1805 return e;
1806 }
1807
1808 self.probe(|_| {
1809 let bound_predicate = predicate.kind();
1814 let (values, err) = match bound_predicate.skip_binder() {
1815 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
1816 let ocx = ObligationCtxt::new(self);
1817
1818 let data = self.instantiate_binder_with_fresh_vars(
1819 obligation.cause.span,
1820 infer::BoundRegionConversionTime::HigherRankedType,
1821 bound_predicate.rebind(data),
1822 );
1823 let unnormalized_term = data.projection_term.to_term(self.tcx, ty::IsRigid::No);
1824 let normalized_term = ocx.normalize(
1825 &obligation.cause,
1826 obligation.param_env,
1827 Unnormalized::new_wip(unnormalized_term),
1828 );
1829
1830 let _ = ocx.try_evaluate_obligations();
1836
1837 if let Err(new_err) =
1838 ocx.eq(&obligation.cause, obligation.param_env, data.term, normalized_term)
1839 {
1840 (
1841 Some((
1842 data.projection_term,
1843 self.deeply_resolve_ignoring_regions(normalized_term),
1844 data.term,
1845 )),
1846 new_err,
1847 )
1848 } else {
1849 (None, error.err)
1850 }
1851 }
1852 _ => (None, error.err),
1853 };
1854
1855 let mut file = None;
1856 let (msg, mut span, mut closure_span) = values
1857 .and_then(|(predicate, normalized_term, expected_term)| {
1858 self.maybe_detailed_projection_msg(
1859 obligation.cause.span,
1860 predicate,
1861 normalized_term,
1862 expected_term,
1863 &mut file,
1864 )
1865 })
1866 .unwrap_or_else(|| {
1867 (
1868 with_forced_trimmed_paths!(format!(
1869 "type mismatch resolving `{}`",
1870 self.tcx.short_string(
1871 self.deeply_resolve_ignoring_regions(predicate),
1872 &mut file
1873 ),
1874 )),
1875 obligation.cause.span,
1876 None,
1877 )
1878 });
1879
1880 if closure_span.is_none()
1884 && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1885 && let Node::Expr(arg_expr) = self.tcx.hir_node(*arg_hir_id)
1886 && let hir::ExprKind::Closure(closure) = arg_expr.kind
1887 && closure.kind == hir::ClosureKind::Closure
1888 {
1889 let body = self.tcx.hir_body(closure.body);
1890 let ret_span = match body.value.kind {
1891 hir::ExprKind::Block(hir::Block { expr: Some(expr), .. }, _) => expr.span,
1892 hir::ExprKind::Block(hir::Block { expr: None, stmts: [.., last], .. }, _) => {
1893 last.span
1894 }
1895 _ => body.value.span,
1896 };
1897 if !closure.fn_decl_span.overlaps(ret_span) {
1898 closure_span = Some(closure.fn_decl_span);
1899 span = ret_span;
1900 }
1901 }
1902
1903 let mut diag = struct_span_code_err!(self.dcx(), span, E0271, "{msg}");
1904 *diag.long_ty_path() = file;
1905 let mut mention_bounds = true;
1906 if let Some(span) = closure_span {
1907 if let Some((_, _, expected_ty)) = values
1908 && let Some(expected_ty) = expected_ty.as_type()
1909 && let ty::Closure(def_id, _) = expected_ty.kind()
1910 && self.tcx.def_span(*def_id).overlaps(span)
1911 && let ObligationCauseCode::FunctionArg { parent_code, arg_hir_id, .. } =
1912 obligation.cause.code()
1913 && let ObligationCauseCode::WhereClauseInExpr(def_id, span, _, _)
1914 | ObligationCauseCode::WhereClause(def_id, span) = &**parent_code
1915 {
1916 let mut multispan: MultiSpan = (*span).into();
1921 multispan.push_span_label(*span, "this requires the closure to return itself");
1922 if let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) {
1923 multispan
1924 .push_span_label(arg.span, "this closure would have to return itself");
1925 }
1926 let in_the_item = match self.tcx.opt_item_name(*def_id) {
1927 Some(name) => format!("in `{name}`"),
1928 None => String::new(),
1929 };
1930 diag.span_note(
1931 multispan,
1932 format!(
1933 "a bound {in_the_item} requires that a closure return itself, which is \
1934 not possible",
1935 ),
1936 );
1937 mention_bounds = false;
1938 } else {
1939 diag.span_label(span, "this closure");
1956 if !span.overlaps(obligation.cause.span) {
1957 diag.span_label(obligation.cause.span, "closure used here");
1959 }
1960 }
1961 }
1962
1963 let secondary_span = self.probe(|_| {
1964 let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1965 predicate.kind().skip_binder()
1966 else {
1967 return None;
1968 };
1969 if !proj.projection_term.kind.is_trait_projection() {
1970 return None;
1971 }
1972
1973 let trait_ref = self.enter_forall_and_leak_universe(
1974 predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)),
1975 );
1976 let Ok(Some(ImplSource::UserDefined(impl_data))) =
1977 SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref))
1978 else {
1979 return None;
1980 };
1981
1982 let Ok(node) =
1983 specialization_graph::assoc_def(self.tcx, impl_data.impl_def_id, proj.def_id())
1984 else {
1985 return None;
1986 };
1987
1988 if !node.is_final() {
1989 return None;
1990 }
1991
1992 match self.tcx.hir_get_if_local(node.item.def_id) {
1993 Some(
1994 hir::Node::TraitItem(hir::TraitItem {
1995 kind: hir::TraitItemKind::Type(_, Some(ty)),
1996 ..
1997 })
1998 | hir::Node::ImplItem(hir::ImplItem {
1999 kind: hir::ImplItemKind::Type(ty),
2000 ..
2001 }),
2002 ) => Some((
2003 ty.span.into(),
2004 with_forced_trimmed_paths!(Cow::from(format!(
2005 "type mismatch resolving `{}`",
2006 self.tcx.short_string(
2007 self.deeply_resolve_ignoring_regions(predicate),
2008 diag.long_ty_path()
2009 ),
2010 ))),
2011 true,
2012 )),
2013 _ => None,
2014 }
2015 });
2016
2017 if let ObligationCauseCode::ReturnType = obligation.cause.code() {
2019 let body = self.tcx.hir_body_owned_by(obligation.cause.body_def_id);
2020 let mut visitor = ReturnsVisitor::default();
2021 visitor.visit_body(&body);
2022 if visitor.returns.is_empty()
2023 && let hir::ExprKind::Block(block, _) = body.value.kind
2024 {
2025 let span = match block.stmts {
2028 [] => body.value.span,
2029 [.., stmt] => stmt.span,
2030 };
2031 if let Some(clause) = predicate.as_clause()
2032 && let ty::ClauseKind::Projection(projection) = clause.kind().skip_binder()
2033 && let Some(ty) = projection.term.as_type()
2034 && ty == self.tcx.types.unit
2035 {
2036 diag.span_label(span, "`()` returned here");
2037 }
2038 } else if let Some(typeck) = &self.typeck_results {
2039 for expr in visitor.returns {
2040 let span = match expr.kind {
2041 hir::ExprKind::Closure(closure) => closure.fn_decl_span,
2042 _ => expr.span,
2043 };
2044 let msg = match typeck.expr_ty_adjusted_opt(expr) {
2045 Some(ty) => {
2046 let ty = self.tcx.short_string(ty, diag.long_ty_path());
2047 format!("`{ty}` returned here")
2048 }
2049 None => "value returned here".to_string(),
2050 };
2051 diag.span_label(span, msg);
2052 self.point_at_chain_in_return_position(
2053 obligation.cause.body_def_id,
2054 expr,
2055 typeck,
2056 obligation.param_env,
2057 &mut diag,
2058 );
2059 }
2060 }
2061 }
2062
2063 self.note_type_err(
2064 &mut diag,
2065 &obligation.cause,
2066 secondary_span,
2067 values.map(|(_, normalized_ty, expected_ty)| {
2068 obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(
2069 expected_ty,
2070 normalized_ty,
2071 )))
2072 }),
2073 err,
2074 false,
2075 Some(span),
2076 );
2077 if mention_bounds {
2078 self.note_obligation_cause(&mut diag, obligation);
2079 }
2080 diag.emit_err()
2081 })
2082 }
2083
2084 fn maybe_detailed_projection_msg(
2085 &self,
2086 mut span: Span,
2087 projection_term: ty::AliasTerm<'tcx>,
2088 normalized_ty: ty::Term<'tcx>,
2089 expected_ty: ty::Term<'tcx>,
2090 long_ty_path: &mut Option<PathBuf>,
2091 ) -> Option<(String, Span, Option<Span>)> {
2092 if !projection_term.kind.is_trait_projection() {
2093 return None;
2094 }
2095
2096 let projection_def_id = projection_term.expect_projection_def_id();
2097 let trait_def_id = projection_term.trait_def_id(self.tcx);
2098 let self_ty = projection_term.self_ty();
2099
2100 {
let _guard = ForceTrimmedGuard::new();
if self.tcx.is_lang_item(projection_def_id, LangItem::FnOnceOutput) {
let (span, closure_span) =
if let ty::Closure(def_id, _) = *self_ty.kind() {
let def_span = self.tcx.def_span(def_id);
if let Some(local_def_id) = def_id.as_local() &&
let node = self.tcx.hir_node_by_def_id(local_def_id) &&
let Some(fn_decl) = node.fn_decl() &&
let Some(id) = node.body_id() {
span =
match fn_decl.output {
hir::FnRetTy::Return(ty) => ty.span,
hir::FnRetTy::DefaultReturn(_) => {
let body = self.tcx.hir_body(id);
match body.value.kind {
hir::ExprKind::Block(hir::Block { expr: Some(expr), .. }, _)
=> expr.span,
hir::ExprKind::Block(hir::Block {
expr: None, stmts: [.., last], .. }, _) => last.span,
_ => body.value.span,
}
}
};
}
(span, Some(def_span))
} else { (span, None) };
let item =
match self_ty.kind() {
ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
_ => self.tcx.short_string(self_ty, long_ty_path),
};
let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
let normalized_ty =
self.tcx.short_string(normalized_ty, long_ty_path);
Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` to return `{1}`, but it returns `{2}`",
item, expected_ty, normalized_ty))
}), span, closure_span))
} else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
let self_ty = self.tcx.short_string(self_ty, long_ty_path);
let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
let normalized_ty =
self.tcx.short_string(normalized_ty, long_ty_path);
Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` to be a future that resolves to `{1}`, but it resolves to `{2}`",
self_ty, expected_ty, normalized_ty))
}), span, None))
} else if Some(trait_def_id) ==
self.tcx.get_diagnostic_item(sym::Iterator) {
let self_ty = self.tcx.short_string(self_ty, long_ty_path);
let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
let normalized_ty =
self.tcx.short_string(normalized_ty, long_ty_path);
Some((::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` to be an iterator that yields `{1}`, but it yields `{2}`",
self_ty, expected_ty, normalized_ty))
}), span, None))
} else { None }
}with_forced_trimmed_paths! {
2101 if self.tcx.is_lang_item(projection_def_id, LangItem::FnOnceOutput) {
2102 let (span, closure_span) = if let ty::Closure(def_id, _) = *self_ty.kind() {
2103 let def_span = self.tcx.def_span(def_id);
2104 if let Some(local_def_id) = def_id.as_local()
2105 && let node = self.tcx.hir_node_by_def_id(local_def_id)
2106 && let Some(fn_decl) = node.fn_decl()
2107 && let Some(id) = node.body_id()
2108 {
2109 span = match fn_decl.output {
2110 hir::FnRetTy::Return(ty) => ty.span,
2111 hir::FnRetTy::DefaultReturn(_) => {
2112 let body = self.tcx.hir_body(id);
2113 match body.value.kind {
2114 hir::ExprKind::Block(
2115 hir::Block { expr: Some(expr), .. },
2116 _,
2117 ) => expr.span,
2118 hir::ExprKind::Block(
2119 hir::Block {
2120 expr: None, stmts: [.., last], ..
2121 },
2122 _,
2123 ) => last.span,
2124 _ => body.value.span,
2125 }
2126 }
2127 };
2128 }
2129 (span, Some(def_span))
2130 } else {
2131 (span, None)
2132 };
2133 let item = match self_ty.kind() {
2134 ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
2135 _ => self.tcx.short_string(self_ty, long_ty_path),
2136 };
2137 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
2138 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
2139 Some((format!(
2140 "expected `{item}` to return `{expected_ty}`, but it returns `{normalized_ty}`",
2141 ), span, closure_span))
2142 } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
2143 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
2144 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
2145 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
2146 Some((format!(
2147 "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
2148 resolves to `{normalized_ty}`"
2149 ), span, None))
2150 } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
2151 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
2152 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
2153 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
2154 Some((format!(
2155 "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
2156 yields `{normalized_ty}`"
2157 ), span, None))
2158 } else {
2159 None
2160 }
2161 }
2162 }
2163
2164 pub fn fuzzy_match_tys(
2165 &self,
2166 mut a: Ty<'tcx>,
2167 mut b: Ty<'tcx>,
2168 ignoring_lifetimes: bool,
2169 ) -> Option<CandidateSimilarity> {
2170 fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
2173 match t.kind() {
2174 ty::Bool => Some(0),
2175 ty::Char => Some(1),
2176 ty::Str => Some(2),
2177 ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => Some(2),
2178 ty::Int(..)
2179 | ty::Uint(..)
2180 | ty::Float(..)
2181 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
2182 ty::Ref(..) | ty::RawPtr(..) => Some(5),
2183 ty::Array(..) | ty::Slice(..) => Some(6),
2184 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
2185 ty::Dynamic(..) => Some(8),
2186 ty::Closure(..) => Some(9),
2187 ty::Tuple(..) => Some(10),
2188 ty::Param(..) => Some(11),
2189 ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. }, .. }) => Some(12),
2190 ty::Alias(_, ty::AliasTy { kind: ty::Inherent { .. }, .. }) => Some(13),
2191 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => Some(14),
2192 ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) => Some(15),
2193 ty::Never => Some(16),
2194 ty::Adt(..) => Some(17),
2195 ty::Coroutine(..) => Some(18),
2196 ty::Foreign(..) => Some(19),
2197 ty::CoroutineWitness(..) => Some(20),
2198 ty::CoroutineClosure(..) => Some(21),
2199 ty::Pat(..) => Some(22),
2200 ty::UnsafeBinder(..) => Some(23),
2201 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
2202
2203 ty::View(..) => ::core::panicking::unimplemented_default_msg()unimplemented!(),
2205 }
2206 }
2207
2208 let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
2209 loop {
2210 match t.kind() {
2211 ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => t = *inner,
2212 _ => break t,
2213 }
2214 }
2215 };
2216
2217 if !ignoring_lifetimes {
2218 a = strip_references(a);
2219 b = strip_references(b);
2220 }
2221
2222 let cat_a = type_category(self.tcx, a)?;
2223 let cat_b = type_category(self.tcx, b)?;
2224 if a == b {
2225 Some(CandidateSimilarity::Exact { ignoring_lifetimes })
2226 } else if cat_a == cat_b {
2227 match (a.kind(), b.kind()) {
2228 (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
2229 (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
2230 (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
2236 self.fuzzy_match_tys(a, b, true).is_some()
2237 }
2238 _ => true,
2239 }
2240 .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
2241 } else if ignoring_lifetimes {
2242 None
2243 } else {
2244 self.fuzzy_match_tys(a, b, true)
2245 }
2246 }
2247
2248 pub(super) fn describe_closure(&self, kind: hir::ClosureKind) -> &'static str {
2249 match kind {
2250 hir::ClosureKind::Closure => "a closure",
2251 hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => "a coroutine",
2252 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2253 hir::CoroutineDesugaring::Async,
2254 hir::CoroutineSource::Block,
2255 )) => "an async block",
2256 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2257 hir::CoroutineDesugaring::Async,
2258 hir::CoroutineSource::Fn,
2259 )) => "an async function",
2260 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2261 hir::CoroutineDesugaring::Async,
2262 hir::CoroutineSource::Closure,
2263 ))
2264 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
2265 "an async closure"
2266 }
2267 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2268 hir::CoroutineDesugaring::AsyncGen,
2269 hir::CoroutineSource::Block,
2270 )) => "an async gen block",
2271 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2272 hir::CoroutineDesugaring::AsyncGen,
2273 hir::CoroutineSource::Fn,
2274 )) => "an async gen function",
2275 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2276 hir::CoroutineDesugaring::AsyncGen,
2277 hir::CoroutineSource::Closure,
2278 ))
2279 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
2280 "an async gen closure"
2281 }
2282 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2283 hir::CoroutineDesugaring::Gen,
2284 hir::CoroutineSource::Block,
2285 )) => "a gen block",
2286 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2287 hir::CoroutineDesugaring::Gen,
2288 hir::CoroutineSource::Fn,
2289 )) => "a gen function",
2290 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2291 hir::CoroutineDesugaring::Gen,
2292 hir::CoroutineSource::Closure,
2293 ))
2294 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => "a gen closure",
2295 }
2296 }
2297
2298 pub(crate) fn find_similar_impl_candidates(
2299 &self,
2300 trait_def_id: DefId,
2301 self_ty: Ty<'tcx>,
2302 ) -> Vec<ImplCandidate<'tcx>> {
2303 let mut candidates: Vec<_> = self
2304 .tcx
2305 .all_impls(trait_def_id)
2306 .filter_map(|def_id| {
2307 let imp = self.tcx.impl_trait_header(def_id);
2308 if imp.polarity != ty::ImplPolarity::Positive
2309 || !self.tcx.is_user_visible_dep(def_id.krate)
2310 {
2311 return None;
2312 }
2313 let imp = imp.trait_ref.skip_binder();
2314
2315 self.fuzzy_match_tys(self_ty, imp.self_ty(), false).map(|similarity| {
2316 ImplCandidate { trait_ref: imp, similarity, impl_def_id: def_id }
2317 })
2318 })
2319 .collect();
2320 if candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
2321 candidates.retain(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. }));
2325 }
2326 candidates
2327 }
2328
2329 pub(super) fn report_similar_impl_candidates(
2330 &self,
2331 impl_candidates: &[ImplCandidate<'tcx>],
2332 obligation: &PredicateObligation<'tcx>,
2333 trait_pred: ty::PolyTraitClause<'tcx>,
2334 body_def_id: LocalDefId,
2335 err: &mut Diag<'_>,
2336 other: bool,
2337 param_env: ty::ParamEnv<'tcx>,
2338 ) -> bool {
2339 let parent_map = self.tcx.visible_parent_map(());
2340 let alternative_candidates = |def_id: DefId| {
2341 let mut impl_candidates: Vec<_> = self
2342 .tcx
2343 .all_impls(def_id)
2344 .filter(|def_id| !self.tcx.do_not_recommend_impl(*def_id))
2346 .map(|def_id| (self.tcx.impl_trait_header(def_id), def_id))
2348 .filter_map(|(header, def_id)| {
2349 (header.polarity == ty::ImplPolarity::Positive
2350 || self.tcx.is_automatically_derived(def_id))
2351 .then(|| (header.trait_ref.instantiate_identity().skip_norm_wip(), def_id))
2352 })
2353 .filter(|(trait_ref, _)| {
2354 let self_ty = trait_ref.self_ty();
2355 if let ty::Param(_) = self_ty.kind() {
2357 false
2358 }
2359 else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
2361 let mut did = def.did();
2365 if self.tcx.visibility(did).is_accessible_from(body_def_id, self.tcx) {
2366 if !did.is_local() {
2368 let mut previously_seen_dids: FxHashSet<DefId> = Default::default();
2369 previously_seen_dids.insert(did);
2370 while let Some(&parent) = parent_map.get(&did)
2371 && let hash_set::Entry::Vacant(v) =
2372 previously_seen_dids.entry(parent)
2373 {
2374 if self.tcx.is_doc_hidden(did) {
2375 return false;
2376 }
2377 v.insert();
2378 did = parent;
2379 }
2380 }
2381 true
2382 } else {
2383 false
2384 }
2385 } else {
2386 true
2387 }
2388 })
2389 .collect();
2390
2391 impl_candidates.sort_by_key(|(tr, _)| tr.to_string());
2392 impl_candidates.dedup();
2393 impl_candidates
2394 };
2395
2396 if let [single] = &impl_candidates
2397 && !self.tcx.do_not_recommend_impl(single.impl_def_id)
2398 {
2399 let self_ty = trait_pred.skip_binder().self_ty();
2400 if !self_ty.has_escaping_bound_vars() {
2401 let self_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
2402 if let ty::Ref(_, inner_ty, _) = self_ty.kind()
2403 && self.can_eq(param_env, single.trait_ref.self_ty(), *inner_ty)
2404 && !self.where_clause_expr_matches_failed_self_ty(obligation, self_ty)
2405 {
2406 return true;
2410 }
2411 }
2412
2413 if self.probe(|_| {
2416 let ocx = ObligationCtxt::new(self);
2417
2418 self.enter_forall(trait_pred, |obligation_trait_ref| {
2419 let impl_args = self.fresh_args_for_item(DUMMY_SP, single.impl_def_id);
2420 let impl_trait_ref = ocx.normalize(
2421 &ObligationCause::dummy(),
2422 param_env,
2423 ty::EarlyBinder::bind(self.tcx, single.trait_ref)
2424 .instantiate(self.tcx, impl_args),
2425 );
2426
2427 ocx.register_obligations(
2428 self.tcx
2429 .clauses_of(single.impl_def_id)
2430 .instantiate(self.tcx, impl_args)
2431 .into_iter()
2432 .map(|(clause, _)| {
2433 Obligation::new(
2434 self.tcx,
2435 ObligationCause::dummy(),
2436 param_env,
2437 clause.skip_norm_wip(),
2438 )
2439 }),
2440 );
2441 if !ocx.try_evaluate_obligations().no_errors() {
2442 return false;
2443 }
2444
2445 let mut terrs = ::alloc::vec::Vec::new()vec![];
2446 for (obligation_arg, impl_arg) in
2447 std::iter::zip(obligation_trait_ref.trait_ref.args, impl_trait_ref.args)
2448 {
2449 if (obligation_arg, impl_arg).references_error() {
2450 return false;
2451 }
2452 if let Err(terr) =
2453 ocx.eq(&ObligationCause::dummy(), param_env, impl_arg, obligation_arg)
2454 {
2455 terrs.push(terr);
2456 }
2457 if !ocx.try_evaluate_obligations().no_errors() {
2458 return false;
2459 }
2460 }
2461
2462 if terrs.len() == impl_trait_ref.args.len() {
2464 return false;
2465 }
2466
2467 let impl_trait_ref = self.deeply_resolve_ignoring_regions(impl_trait_ref);
2468 if impl_trait_ref.references_error() {
2469 return false;
2470 }
2471
2472 if let [child, ..] = &err.children[..]
2473 && child.level == Sublevel::Help
2474 && let Some(line) = child.messages.get(0)
2475 && let Some(line) = line.0.as_str()
2476 && line.starts_with("the trait")
2477 && line.contains("is not implemented for")
2478 {
2479 err.children.remove(0);
2486 }
2487
2488 let traits = self.cmp_traits(
2489 obligation_trait_ref.def_id(),
2490 &obligation_trait_ref.trait_ref.args.as_slice()[1..],
2491 impl_trait_ref.def_id,
2492 &impl_trait_ref.args.as_slice()[1..],
2493 );
2494 let traits_content = (traits.0.content(), traits.1.content());
2495 let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty());
2496 let types_content = (types.0.content(), types.1.content());
2497 let mut msg = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal("the trait `")]))vec![StringPart::normal("the trait `")];
2498 if traits_content.0 == traits_content.1 {
2499 msg.push(StringPart::normal(
2500 impl_trait_ref.print_trait_sugared().to_string(),
2501 ));
2502 } else {
2503 msg.extend(traits.0.0);
2504 }
2505 msg.extend([
2506 StringPart::normal("` "),
2507 StringPart::highlighted("is not"),
2508 StringPart::normal(" implemented for `"),
2509 ]);
2510 if types_content.0 == types_content.1 {
2511 let ty = self
2512 .tcx
2513 .short_string(obligation_trait_ref.self_ty(), err.long_ty_path());
2514 msg.push(StringPart::normal(ty));
2515 } else {
2516 msg.extend(types.0.0);
2517 }
2518 msg.push(StringPart::normal("`"));
2519 if types_content.0 == types_content.1 {
2520 msg.push(StringPart::normal("\nbut trait `"));
2521 msg.extend(traits.1.0);
2522 msg.extend([
2523 StringPart::normal("` "),
2524 StringPart::highlighted("is"),
2525 StringPart::normal(" implemented for it"),
2526 ]);
2527 } else if traits_content.0 == traits_content.1 {
2528 msg.extend([
2529 StringPart::normal("\nbut it "),
2530 StringPart::highlighted("is"),
2531 StringPart::normal(" implemented for `"),
2532 ]);
2533 msg.extend(types.1.0);
2534 msg.push(StringPart::normal("`"));
2535 } else {
2536 msg.push(StringPart::normal("\nbut trait `"));
2537 msg.extend(traits.1.0);
2538 msg.extend([
2539 StringPart::normal("` "),
2540 StringPart::highlighted("is"),
2541 StringPart::normal(" implemented for `"),
2542 ]);
2543 msg.extend(types.1.0);
2544 msg.push(StringPart::normal("`"));
2545 }
2546 err.highlighted_span_help(self.tcx.def_span(single.impl_def_id), msg);
2547
2548 if let [TypeError::Sorts(exp_found)] = &terrs[..] {
2549 let exp_found = self.deeply_resolve_ignoring_regions(*exp_found);
2550 let expected =
2551 self.tcx.short_string(exp_found.expected, err.long_ty_path());
2552 let found = self.tcx.short_string(exp_found.found, err.long_ty_path());
2553 err.highlighted_help(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal("for that trait implementation, "),
StringPart::normal("expected `"),
StringPart::highlighted(expected),
StringPart::normal("`, found `"),
StringPart::highlighted(found), StringPart::normal("`")]))vec![
2554 StringPart::normal("for that trait implementation, "),
2555 StringPart::normal("expected `"),
2556 StringPart::highlighted(expected),
2557 StringPart::normal("`, found `"),
2558 StringPart::highlighted(found),
2559 StringPart::normal("`"),
2560 ]);
2561 self.suggest_function_pointers_impl(None, &exp_found, err);
2562 }
2563
2564 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2565 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2566 && !crates.is_empty()
2567 {
2568 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2569 err.help("you can use `cargo tree` to explore your dependency tree");
2570 }
2571 true
2572 })
2573 }) {
2574 return true;
2575 }
2576 }
2577
2578 let other = if other { "other " } else { "" };
2579 let report = |mut candidates: Vec<(TraitRef<'tcx>, DefId)>, err: &mut Diag<'_>| {
2580 candidates.retain(|(tr, _)| !tr.references_error());
2581 if candidates.is_empty() {
2582 return false;
2583 }
2584 let mut specific_candidates = candidates.clone();
2585 specific_candidates.retain(|(tr, _)| {
2586 tr.with_replaced_self_ty(self.tcx, trait_pred.skip_binder().self_ty())
2587 == trait_pred.skip_binder().trait_ref
2588 });
2589 if !specific_candidates.is_empty() {
2590 candidates = specific_candidates;
2593 }
2594 if let &[(cand, def_id)] = &candidates[..] {
2595 if self.tcx.is_diagnostic_item(sym::FromResidual, cand.def_id)
2596 && !self.tcx.features().enabled(sym::try_trait_v2)
2597 {
2598 return false;
2599 }
2600 let mut multi_span = MultiSpan::from_span(self.tcx.def_span(def_id));
2601 let (desc, mention_castable) =
2602 match (cand.self_ty().kind(), trait_pred.self_ty().skip_binder().kind()) {
2603 (ty::FnPtr(..), ty::FnDef(..)) => {
2604 (" implemented for fn pointer `", ", cast using `as`")
2605 }
2606 (ty::FnPtr(..), _) => (" implemented for fn pointer `", ""),
2607 _ => {
2608 let evaluate_obligations = || {
2609 let ocx = ObligationCtxt::new_with_diagnostics(self);
2610 self.enter_forall(trait_pred, |obligation_trait_ref| {
2611 let impl_args = self.fresh_args_for_item(DUMMY_SP, def_id);
2612 let impl_trait_ref = ocx.normalize(
2613 &ObligationCause::dummy(),
2614 param_env,
2615 ty::EarlyBinder::bind(self.tcx, cand)
2616 .instantiate(self.tcx, impl_args),
2617 );
2618 if ocx
2619 .eq(
2620 &ObligationCause::dummy(),
2621 param_env,
2622 obligation_trait_ref.trait_ref,
2623 impl_trait_ref,
2624 )
2625 .is_err()
2626 {
2627 return TraitErrors::NoErrors;
2628 }
2629 ocx.register_obligations(
2630 self.tcx
2631 .clauses_of(def_id)
2632 .instantiate(self.tcx, impl_args)
2633 .into_iter()
2634 .map(|(clause, span)| {
2635 Obligation::new(
2636 self.tcx,
2637 ObligationCause::dummy_with_span(span),
2638 param_env,
2639 clause.skip_normalization(),
2640 )
2641 }),
2642 );
2643 ocx.try_evaluate_obligations()
2644 })
2645 };
2646 let failing_obligations =
2647 if !self.tcx.clauses_of(def_id).clauses.is_empty() {
2648 self.probe(|_| evaluate_obligations())
2649 } else {
2650 TraitErrors::NoErrors
2651 };
2652
2653 if failing_obligations.no_errors() {
2654 (" implemented for `", "")
2655 } else {
2656 for error in failing_obligations {
2657 multi_span.push_span_label(
2658 error.root_obligation.cause.span,
2659 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied requirement introduced here: `{0}`",
self.tcx.short_string(error.root_obligation.predicate,
err.long_ty_path())))
})format!(
2660 "unsatisfied requirement introduced here: `{}`",
2661 self.tcx.short_string(
2662 error.root_obligation.predicate,
2663 err.long_ty_path()
2664 ),
2665 ),
2666 );
2667 }
2668
2669 (" conditionally implemented for `", "")
2670 }
2671 }
2672 };
2673 let trait_ = self.tcx.short_string(cand.print_trait_sugared(), err.long_ty_path());
2674 let self_ty = self.tcx.short_string(cand.self_ty(), err.long_ty_path());
2675 err.highlighted_span_help(
2676 multi_span,
2677 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait `{0}` ",
trait_))
})), StringPart::highlighted("is"),
StringPart::normal(desc), StringPart::highlighted(self_ty),
StringPart::normal("`"),
StringPart::normal(mention_castable)]))vec![
2678 StringPart::normal(format!("the trait `{trait_}` ")),
2679 StringPart::highlighted("is"),
2680 StringPart::normal(desc),
2681 StringPart::highlighted(self_ty),
2682 StringPart::normal("`"),
2683 StringPart::normal(mention_castable),
2684 ],
2685 );
2686 return true;
2687 }
2688 let trait_ref = TraitRef::identity(self.tcx, candidates[0].0.def_id);
2689 let mut traits: Vec<_> =
2691 candidates.iter().map(|(c, _)| c.print_only_trait_path().to_string()).collect();
2692 traits.sort();
2693 traits.dedup();
2694 let all_traits_equal = traits.len() == 1;
2697 let mut types: Vec<_> =
2698 candidates.iter().map(|(c, _)| c.self_ty().to_string()).collect();
2699 types.sort();
2700 types.dedup();
2701 let all_types_equal = types.len() == 1;
2702
2703 if candidates.len() < 5 {
2704 let spans: Vec<_> =
2705 candidates.iter().map(|&(_, def_id)| self.tcx.def_span(def_id)).collect();
2706 let mut span: MultiSpan = spans.into();
2707 for (c, def_id) in &candidates {
2708 let msg = if all_traits_equal {
2709 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.short_string(c.self_ty(), err.long_ty_path())))
})format!("`{}`", self.tcx.short_string(c.self_ty(), err.long_ty_path()))
2710 } else if all_types_equal {
2711 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2712 "`{}`",
2713 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path())
2714 )
2715 } else {
2716 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements `{1}`",
self.tcx.short_string(c.self_ty(), err.long_ty_path()),
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2717 "`{}` implements `{}`",
2718 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2719 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path()),
2720 )
2721 };
2722 span.push_span_label(self.tcx.def_span(*def_id), msg);
2723 }
2724 let msg = if all_types_equal {
2725 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements trait `{1}`",
self.tcx.short_string(candidates[0].0.self_ty(),
err.long_ty_path()),
self.tcx.short_string(trait_ref.print_trait_sugared(),
err.long_ty_path())))
})format!(
2726 "`{}` implements trait `{}`",
2727 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2728 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2729 )
2730 } else {
2731 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following {1}types implement trait `{0}`",
self.tcx.short_string(trait_ref.print_trait_sugared(),
err.long_ty_path()), other))
})format!(
2732 "the following {other}types implement trait `{}`",
2733 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2734 )
2735 };
2736 err.span_help(span, msg);
2737 } else {
2738 let mut tuple_min_arity = usize::MAX;
2744 let mut tuple_max_arity = 0_usize;
2745 let mut last_arity = None;
2746 let mut all_tuples_cont_arity = true;
2747 candidates.sort_by(|(c1, _), (c2, _)| {
2748 if let ty::Tuple(tys1) = c1.self_ty().kind()
2749 && let ty::Tuple(tys2) = c2.self_ty().kind()
2750 {
2751 tys1.len().cmp(&tys2.len())
2752 } else {
2753 std::cmp::Ordering::Equal
2754 }
2755 });
2756
2757 let mut candidate_names: Vec<String> = candidates
2758 .iter()
2759 .map(|(c, _)| {
2760 if all_traits_equal {
2761 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n {0}",
self.tcx.short_string(c.self_ty(), err.long_ty_path())))
})format!(
2762 "\n {}",
2763 self.tcx.short_string(c.self_ty(), err.long_ty_path())
2764 )
2765 } else if all_types_equal {
2766 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n {0}",
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2767 "\n {}",
2768 self.tcx
2769 .short_string(c.print_only_trait_path(), err.long_ty_path())
2770 )
2771 } else {
2772 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n `{0}` implements `{1}`",
self.tcx.short_string(c.self_ty(), err.long_ty_path()),
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2773 "\n `{}` implements `{}`",
2774 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2775 self.tcx
2776 .short_string(c.print_only_trait_path(), err.long_ty_path()),
2777 )
2778 }
2779 })
2780 .collect();
2781
2782 let mut all_tuples_impl_the_same_trait = true;
2783 let mut last_tuple_trait_ref = None;
2784
2785 fn have_same_trait_path(a: &TraitRef<'_>, b: &TraitRef<'_>) -> bool {
2786 a.print_only_trait_path().to_string() == b.print_only_trait_path().to_string()
2787 }
2788 let (tuples_candidates, tuples_range) = {
2793 let tuples_indexes: Vec<usize> = candidates
2794 .iter()
2795 .enumerate()
2796 .filter_map(|(idx, (c, _))| {
2797 if let ty::Tuple(tys) = c.self_ty().kind() {
2798 if all_tuples_cont_arity
2799 && last_arity.map_or(1, |a: usize| a.abs_diff(tys.len())) == 1
2800 {
2801 last_arity = Some(tys.len());
2802 if tys.len() > tuple_max_arity {
2803 tuple_max_arity = tys.len();
2804 }
2805 if tys.len() < tuple_min_arity {
2806 tuple_min_arity = tys.len();
2807 }
2808 if all_tuples_impl_the_same_trait
2809 && have_same_trait_path(
2810 last_tuple_trait_ref.map_or(c, |e: &TraitRef<'_>| e),
2811 c,
2812 )
2813 {
2814 last_tuple_trait_ref = Some(c);
2815 } else {
2816 all_tuples_impl_the_same_trait = false;
2817 }
2818 } else {
2819 all_tuples_cont_arity = false;
2820 }
2821 Some(idx)
2822 } else {
2823 None
2824 }
2825 })
2826 .collect();
2827 let (start, end) = (
2828 tuples_indexes.first().map_or_default(|idx| *idx),
2829 tuples_indexes.last().map_or_default(|idx| *idx + 1),
2830 );
2831 (&candidates[start..end], start..end)
2832 };
2833
2834 if !tuples_candidates.is_empty()
2839 && all_tuples_cont_arity
2840 && (all_traits_equal || all_tuples_impl_the_same_trait)
2841 {
2842 let details = if tuple_min_arity == 0 {
2843 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("up to tuples of arity {0}",
tuple_max_arity))
})format!("up to tuples of arity {tuple_max_arity}")
2844 } else if !all_traits_equal {
2845 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("for tuples of arity {0} to {1}",
tuple_min_arity, tuple_max_arity))
})format!("for tuples of arity {tuple_min_arity} to {tuple_max_arity}")
2846 } else {
2847 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("for tuples of arity {0} up to and including {1}",
tuple_min_arity, tuple_max_arity))
})format!(
2848 "for tuples of arity {tuple_min_arity} up to and including {tuple_max_arity}"
2849 )
2850 };
2851 let impl_trait = if all_traits_equal {
2852 String::new()
2853 } else {
2854 let c = tuples_candidates[0].0;
2855 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" implements `{0}`",
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2856 " implements `{}`",
2857 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path())
2858 )
2859 };
2860 let simplified_output = [
2861 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n `(T₁, T₂, …, Tₙ)` {0}{1}",
details, impl_trait))
})format!("\n `(T\u{2081}, T\u{2082}, …, T\u{2099})` {details}{impl_trait}"),
2863 ];
2864 candidate_names.splice(tuples_range, simplified_output);
2865 }
2866
2867 let end = if candidate_names.len() <= 9 || self.tcx.sess.opts.verbose {
2868 candidate_names.len()
2869 } else {
2870 8
2871 };
2872
2873 let msg = if all_types_equal {
2874 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements trait `{1}`",
self.tcx.short_string(candidates[0].0.self_ty(),
err.long_ty_path()),
self.tcx.short_string(trait_ref.print_trait_sugared(),
err.long_ty_path())))
})format!(
2875 "`{}` implements trait `{}`",
2876 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2877 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2878 )
2879 } else {
2880 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the following {1}types implement trait `{0}`",
self.tcx.short_string(trait_ref.print_trait_sugared(),
err.long_ty_path()), other))
})format!(
2881 "the following {other}types implement trait `{}`",
2882 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2883 )
2884 };
2885
2886 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{2}:{0}{1}",
candidate_names[..end].join(""),
if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\nand {0} others",
candidates.len() - 8))
})
} else { String::new() }, msg))
})format!(
2887 "{msg}:{}{}",
2888 candidate_names[..end].join(""),
2889 if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
2890 format!("\nand {} others", candidates.len() - 8)
2891 } else {
2892 String::new()
2893 }
2894 ));
2895 }
2896
2897 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2898 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2899 && !crates.is_empty()
2900 {
2901 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2902 err.help("you can use `cargo tree` to explore your dependency tree");
2903 }
2904 true
2905 };
2906
2907 let impl_candidates = impl_candidates
2910 .into_iter()
2911 .cloned()
2912 .filter(|cand| !self.tcx.do_not_recommend_impl(cand.impl_def_id))
2913 .collect::<Vec<_>>();
2914
2915 let def_id = trait_pred.def_id();
2916 if impl_candidates.is_empty() {
2917 if self.tcx.trait_is_auto(def_id)
2918 || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2919 || self.tcx.get_diagnostic_name(def_id).is_some()
2920 {
2921 return false;
2923 }
2924 return report(alternative_candidates(def_id), err);
2925 }
2926
2927 let mut impl_candidates: Vec<_> = impl_candidates
2934 .iter()
2935 .cloned()
2936 .filter(|cand| !cand.trait_ref.references_error())
2937 .map(|mut cand| {
2938 cand.trait_ref = self
2942 .tcx
2943 .try_normalize_erasing_regions(
2944 ty::TypingEnv::non_body_analysis(self.tcx, cand.impl_def_id),
2945 Unnormalized::new_wip(cand.trait_ref),
2946 )
2947 .unwrap_or(cand.trait_ref);
2948 cand
2949 })
2950 .collect();
2951 impl_candidates.sort_by_key(|cand| {
2952 let len = if let GenericArgKind::Type(ty) = cand.trait_ref.args[0].kind()
2954 && let ty::Array(_, len) = ty.kind()
2955 {
2956 len.try_to_target_usize(self.tcx).unwrap_or(u64::MAX)
2958 } else {
2959 0
2960 };
2961
2962 (cand.similarity, len, cand.trait_ref.to_string())
2963 });
2964 let mut impl_candidates: Vec<_> =
2965 impl_candidates.into_iter().map(|cand| (cand.trait_ref, cand.impl_def_id)).collect();
2966 impl_candidates.dedup();
2967
2968 report(impl_candidates, err)
2969 }
2970
2971 fn report_similar_impl_candidates_for_root_obligation(
2972 &self,
2973 obligation: &PredicateObligation<'tcx>,
2974 trait_predicate: ty::Binder<'tcx, ty::TraitClause<'tcx>>,
2975 body_def_id: LocalDefId,
2976 err: &mut Diag<'_>,
2977 ) {
2978 let mut code = obligation.cause.code();
2985 let mut trait_pred = trait_predicate;
2986 let mut peeled = false;
2987 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
2988 code = parent_code;
2989 if let Some(parent_trait_pred) = parent_trait_pred {
2990 trait_pred = parent_trait_pred;
2991 peeled = true;
2992 }
2993 }
2994 let def_id = trait_pred.def_id();
2995 if peeled && !self.tcx.trait_is_auto(def_id) && self.tcx.as_lang_item(def_id).is_none() {
3001 let impl_candidates = self.find_similar_impl_candidates(
3002 trait_pred.def_id(),
3003 trait_pred.self_ty().skip_binder(),
3004 );
3005 self.report_similar_impl_candidates(
3006 &impl_candidates,
3007 obligation,
3008 trait_pred,
3009 body_def_id,
3010 err,
3011 true,
3012 obligation.param_env,
3013 );
3014 }
3015 }
3016
3017 fn get_parent_trait_ref(
3019 &self,
3020 code: &ObligationCauseCode<'tcx>,
3021 ) -> Option<(Ty<'tcx>, Option<Span>)> {
3022 match code {
3023 ObligationCauseCode::BuiltinDerived(data) => {
3024 let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
3025 match self.get_parent_trait_ref(&data.parent_code) {
3026 Some(t) => Some(t),
3027 None => {
3028 let ty = parent_trait_ref.skip_binder().self_ty();
3029 let span = TyCategory::from_ty(self.tcx, ty)
3030 .map(|(_, def_id)| self.tcx.def_span(def_id));
3031 Some((ty, span))
3032 }
3033 }
3034 }
3035 ObligationCauseCode::FunctionArg { parent_code, .. } => {
3036 self.get_parent_trait_ref(parent_code)
3037 }
3038 _ => None,
3039 }
3040 }
3041
3042 fn check_same_trait_different_version(
3043 &self,
3044 err: &mut Diag<'_>,
3045 trait_pred: ty::PolyTraitClause<'tcx>,
3046 ) -> bool {
3047 let get_trait_impls = |trait_def_id| {
3048 let mut trait_impls = ::alloc::vec::Vec::new()vec![];
3049 self.tcx.for_each_relevant_impl(
3050 trait_def_id,
3051 trait_pred.skip_binder().self_ty(),
3052 |impl_def_id| {
3053 let impl_trait_header = self.tcx.impl_trait_header(impl_def_id);
3054 trait_impls
3055 .push(self.tcx.def_span(impl_trait_header.trait_ref.skip_binder().def_id));
3056 },
3057 );
3058 trait_impls
3059 };
3060 self.check_same_definition_different_crate(
3061 err,
3062 trait_pred.def_id(),
3063 self.tcx.visible_traits(),
3064 get_trait_impls,
3065 "trait",
3066 )
3067 }
3068
3069 pub fn note_two_crate_versions(
3070 &self,
3071 krate: CrateNum,
3072 sp: impl Into<MultiSpan>,
3073 err: &mut Diag<'_>,
3074 ) {
3075 let crate_name = self.tcx.crate_name(krate);
3076 let crate_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("there are multiple different versions of crate `{0}` in the dependency graph",
crate_name))
})format!(
3077 "there are multiple different versions of crate `{crate_name}` in the dependency graph"
3078 );
3079 err.span_note(sp, crate_msg);
3080 }
3081
3082 fn note_adt_version_mismatch(&self, err: &mut Diag<'_>, trait_pred: ty::PolyTraitClause<'tcx>) {
3083 let ty::Adt(impl_self_def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
3084 else {
3085 return;
3086 };
3087
3088 let impl_self_did = impl_self_def.did();
3089
3090 if impl_self_did.krate == LOCAL_CRATE {
3093 return;
3094 }
3095
3096 let impl_self_path = self.comparable_path(impl_self_did);
3097 let impl_self_crate_name = self.tcx.crate_name(impl_self_did.krate);
3098 let similar_items: UnordSet<_> = self
3099 .tcx
3100 .visible_parent_map(())
3101 .items()
3102 .filter_map(|(&item, _)| {
3103 if impl_self_did == item {
3105 return None;
3106 }
3107 if item.krate == LOCAL_CRATE {
3110 return None;
3111 }
3112 if impl_self_crate_name != self.tcx.crate_name(item.krate) {
3115 return None;
3116 }
3117 if !self.tcx.def_kind(item).is_adt() {
3120 return None;
3121 }
3122 let path = self.comparable_path(item);
3123 let is_similar = path.ends_with(&impl_self_path) || impl_self_path.ends_with(&path);
3126 is_similar.then_some((item, path))
3127 })
3128 .collect();
3129
3130 let mut similar_items =
3131 similar_items.into_items().into_sorted_stable_ord_by_key(|(_, path)| path);
3132 similar_items.dedup();
3133
3134 for (similar_item, _) in similar_items {
3135 err.span_help(self.tcx.def_span(similar_item), "item with same name found");
3136 self.note_two_crate_versions(similar_item.krate, MultiSpan::new(), err);
3137 }
3138 }
3139
3140 fn check_same_name_different_path(
3141 &self,
3142 err: &mut Diag<'_>,
3143 obligation: &PredicateObligation<'tcx>,
3144 trait_pred: ty::PolyTraitClause<'tcx>,
3145 ) -> bool {
3146 let mut suggested = false;
3147 let trait_def_id = trait_pred.def_id();
3148 let trait_has_same_params = |other_trait_def_id: DefId| -> bool {
3149 let trait_generics = self.tcx.generics_of(trait_def_id);
3150 let other_trait_generics = self.tcx.generics_of(other_trait_def_id);
3151
3152 if trait_generics.count() != other_trait_generics.count() {
3153 return false;
3154 }
3155 trait_generics.own_params.iter().zip(other_trait_generics.own_params.iter()).all(
3156 |(a, b)| match (&a.kind, &b.kind) {
3157 (ty::GenericParamDefKind::Lifetime, ty::GenericParamDefKind::Lifetime)
3158 | (
3159 ty::GenericParamDefKind::Type { .. },
3160 ty::GenericParamDefKind::Type { .. },
3161 )
3162 | (
3163 ty::GenericParamDefKind::Const { .. },
3164 ty::GenericParamDefKind::Const { .. },
3165 ) => true,
3166 _ => false,
3167 },
3168 )
3169 };
3170 let trait_name = self.tcx.item_name(trait_def_id);
3171 if let Some(other_trait_def_id) = self.tcx.all_traits_including_private().find(|&def_id| {
3172 trait_def_id != def_id
3173 && trait_name == self.tcx.item_name(def_id)
3174 && trait_has_same_params(def_id)
3175 && !self.tcx.is_lang_item(def_id, LangItem::PointeeSized)
3177 && self.predicate_must_hold_modulo_regions(&Obligation::new(
3178 self.tcx,
3179 obligation.cause.clone(),
3180 obligation.param_env,
3181 trait_pred.map_bound(|tr| ty::TraitClause {
3182 trait_ref: ty::TraitRef::new(self.tcx, def_id, tr.trait_ref.args),
3183 ..tr
3184 }),
3185 ))
3186 }) {
3187 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements similarly named trait `{1}`, but not `{2}`",
trait_pred.self_ty(),
self.tcx.def_path_str(other_trait_def_id),
trait_pred.print_modifiers_and_trait_path()))
})format!(
3188 "`{}` implements similarly named trait `{}`, but not `{}`",
3189 trait_pred.self_ty(),
3190 self.tcx.def_path_str(other_trait_def_id),
3191 trait_pred.print_modifiers_and_trait_path()
3192 ));
3193 suggested = true;
3194 }
3195 suggested
3196 }
3197
3198 pub fn note_different_trait_with_same_name(
3203 &self,
3204 err: &mut Diag<'_>,
3205 obligation: &PredicateObligation<'tcx>,
3206 trait_pred: ty::PolyTraitClause<'tcx>,
3207 ) -> bool {
3208 if self.check_same_trait_different_version(err, trait_pred) {
3209 return true;
3210 }
3211 self.check_same_name_different_path(err, obligation, trait_pred)
3212 }
3213
3214 fn comparable_path(&self, did: DefId) -> String {
3217 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}",
self.tcx.def_path_str(did)))
})format!("::{}", self.tcx.def_path_str(did))
3218 }
3219
3220 pub(super) fn mk_trait_obligation_with_new_self_ty(
3225 &self,
3226 param_env: ty::ParamEnv<'tcx>,
3227 trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitClause<'tcx>, Ty<'tcx>)>,
3228 ) -> PredicateObligation<'tcx> {
3229 let trait_pred = trait_ref_and_ty
3230 .map_bound(|(tr, new_self_ty)| tr.with_replaced_self_ty(self.tcx, new_self_ty));
3231
3232 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
3233 }
3234
3235 fn predicate_can_apply(
3238 &self,
3239 param_env: ty::ParamEnv<'tcx>,
3240 pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + TypeFoldable<TyCtxt<'tcx>>,
3241 ) -> bool {
3242 struct ParamToVarFolder<'a, 'tcx> {
3243 infcx: &'a InferCtxt<'tcx>,
3244 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
3245 }
3246
3247 impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
3248 fn cx(&self) -> TyCtxt<'tcx> {
3249 self.infcx.tcx
3250 }
3251
3252 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
3256 match ty.kind() {
3257 ty::Param(_) => {
3258 let infcx = self.infcx;
3259 *self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
3260 }
3261 &ty::Alias(is_rigid, alias)
3265 if is_rigid == ty::IsRigid::Yes
3266 && ty.has_type_flags(ty::TypeFlags::HAS_TY_PARAM) =>
3267 {
3268 let alias = alias.fold_with(self);
3269 Ty::new_alias(self.cx(), ty::IsRigid::No, alias)
3270 }
3271 _ => ty.super_fold_with(self),
3272 }
3273 }
3274 }
3275
3276 self.probe(|_| {
3277 let cleaned_pred =
3278 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
3279
3280 let InferOk { value: cleaned_pred, .. } = self
3281 .infcx
3282 .at(&ObligationCause::dummy(), param_env)
3283 .normalize(Unnormalized::new_wip(cleaned_pred));
3284
3285 let obligation =
3286 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
3287
3288 self.predicate_may_hold(&obligation)
3289 })
3290 }
3291
3292 fn suggest_change_mut_ref_for_closure(
3293 &self,
3294 err: &mut Diag<'_>,
3295 obligation: &PredicateObligation<'tcx>,
3296 ) {
3297 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
3298 && let (_, Some(root_trait_pred)) =
3299 obligation.cause.code().peel_derives_with_predicate()
3300 && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
3301 && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, _) = arg.kind
3302 {
3303 let mut obligation = obligation.clone();
3304 obligation.cause.span = arg.span;
3307 self.suggest_change_mut(&obligation, err, root_trait_pred);
3308 }
3309 }
3310
3311 fn suggest_remove_ref_for_closure(
3312 &self,
3313 err: &mut Diag<'_>,
3314 obligation: &PredicateObligation<'tcx>,
3315 ) {
3316 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
3317 && let (_, Some(root_trait_pred)) =
3318 obligation.cause.code().peel_derives_with_predicate()
3319 && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
3320 && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, _, _) = arg.kind
3321 {
3322 let mut obligation = obligation.clone();
3323 obligation.cause.span = arg.span;
3326
3327 self.suggest_remove_reference(&obligation, err, root_trait_pred);
3328 }
3329 }
3330
3331 fn silence_redundant_cause(
3335 &self,
3336 err: &mut Diag<'_>,
3337 obligation: &PredicateObligation<'tcx>,
3338 root_obligation: &PredicateObligation<'tcx>,
3339 ) {
3340 let hir_id = match root_obligation.cause.code() {
3341 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(hir_id))
3342 | ObligationCauseCode::VariableType(hir_id)
3343 | ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, _)
3344 | ObligationCauseCode::SizedCallReturnType(hir_id) => *hir_id,
3345 ObligationCauseCode::WellFormed(WellFormedLoc::Param { function, .. }) => {
3346 self.tcx.local_def_id_to_hir_id(*function)
3347 }
3348 _ => return,
3349 };
3350
3351 let pred = self.tcx.erase_and_anonymize_regions(obligation.predicate);
3353
3354 if let Some(preds) = self.reported_hir_errors.borrow().get(&hir_id)
3356 && preds.contains(&pred)
3357 {
3358 err.downgrade_to_delayed_bug();
3359 } else {
3360 self.reported_hir_errors.borrow_mut().entry(hir_id).or_default().insert(pred);
3361 }
3362
3363 for (_, node) in self.tcx.hir_parent_iter(hir_id) {
3366 let hir_id = match node {
3367 hir::Node::LetStmt(stmt) => stmt.hir_id,
3368 hir::Node::Stmt(stmt) => stmt.hir_id,
3369 hir::Node::Crate(_)
3370 | hir::Node::Item(_)
3371 | hir::Node::ImplItem(_)
3372 | hir::Node::TraitItem(_) => break,
3373 _ => continue,
3374 };
3375 if let Some(preds) = self.reported_hir_errors.borrow().get(&hir_id)
3376 && preds.contains(&pred)
3377 {
3378 err.downgrade_to_delayed_bug();
3379 } else {
3380 self.reported_hir_errors.borrow_mut().entry(hir_id).or_default().insert(pred);
3381 }
3382 break;
3383 }
3384 }
3385
3386 pub fn note_obligation_cause(
3387 &self,
3388 err: &mut Diag<'_>,
3389 obligation: &PredicateObligation<'tcx>,
3390 ) {
3391 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
3394 self.note_obligation_cause_code(
3395 obligation.cause.body_def_id,
3396 err,
3397 obligation.predicate,
3398 obligation.param_env,
3399 obligation.cause.code(),
3400 &mut ::alloc::vec::Vec::new()vec![],
3401 &mut Default::default(),
3402 );
3403 self.suggest_swapping_lhs_and_rhs(
3404 err,
3405 obligation.predicate,
3406 obligation.param_env,
3407 obligation.cause.code(),
3408 );
3409 self.suggest_borrow_for_unsized_closure_return(
3410 obligation.cause.body_def_id,
3411 err,
3412 obligation.predicate,
3413 );
3414 self.suggest_unsized_bound_if_applicable(err, obligation);
3415 if let Some(span) = err.span.primary_span()
3416 && self
3417 .tcx
3418 .resolutions(())
3419 .paths_matching_assoc_types
3420 .contains(&span.with_parent(None))
3421 {
3422 err.subdiagnostic(AssocTypeWithSameName { span: span.shrink_to_lo() });
3423 }
3424 }
3425 }
3426
3427 pub(super) fn is_recursive_obligation(
3428 &self,
3429 obligated_types: &mut Vec<Ty<'tcx>>,
3430 cause_code: &ObligationCauseCode<'tcx>,
3431 ) -> bool {
3432 if let ObligationCauseCode::BuiltinDerived(data) = cause_code {
3433 let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
3434 let self_ty = parent_trait_ref.skip_binder().self_ty();
3435 if obligated_types.iter().any(|ot| ot == &self_ty) {
3436 return true;
3437 }
3438 if let ty::Adt(def, args) = self_ty.kind()
3439 && let [arg] = &args.as_slice()
3440 && let ty::GenericArgKind::Type(ty) = arg.kind()
3441 && let ty::Adt(inner_def, _) = ty.kind()
3442 && inner_def == def
3443 {
3444 return true;
3445 }
3446 }
3447 false
3448 }
3449
3450 fn get_standard_error_message(
3451 &self,
3452 trait_predicate: ty::PolyTraitClause<'tcx>,
3453 predicate_constness: Option<ty::BoundConstness>,
3454 post_message: String,
3455 long_ty_path: &mut Option<PathBuf>,
3456 ) -> String {
3457 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the trait bound `{0}` is not satisfied{1}",
self.tcx.short_string(trait_predicate.print_with_bound_constness(predicate_constness),
long_ty_path), post_message))
})format!(
3458 "the trait bound `{}` is not satisfied{post_message}",
3459 self.tcx.short_string(
3460 trait_predicate.print_with_bound_constness(predicate_constness),
3461 long_ty_path,
3462 ),
3463 )
3464 }
3465
3466 fn select_transmute_obligation_for_reporting(
3467 &self,
3468 obligation: &PredicateObligation<'tcx>,
3469 trait_predicate: ty::PolyTraitClause<'tcx>,
3470 root_obligation: &PredicateObligation<'tcx>,
3471 ) -> (PredicateObligation<'tcx>, ty::PolyTraitClause<'tcx>) {
3472 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
3473 return (obligation.clone(), trait_predicate);
3474 }
3475
3476 let ocx = ObligationCtxt::new(self);
3477 let normalized_predicate = self.tcx.erase_and_anonymize_regions(
3478 self.tcx.instantiate_bound_regions_with_erased(trait_predicate),
3479 );
3480 let trait_ref = normalized_predicate.trait_ref;
3481
3482 let assume = ocx.normalize(
3483 &obligation.cause,
3484 obligation.param_env,
3485 Unnormalized::new_wip(trait_ref.args.const_at(2)),
3486 );
3487
3488 let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
3489 return (obligation.clone(), trait_predicate);
3490 };
3491
3492 let is_normalized_yes = #[allow(non_exhaustive_omitted_patterns)] match rustc_transmute::TransmuteTypeEnv::new(self.tcx).is_transmutable(trait_ref.args.type_at(1),
trait_ref.args.type_at(0), assume) {
Answer::Yes => true,
_ => false,
}matches!(
3493 rustc_transmute::TransmuteTypeEnv::new(self.tcx).is_transmutable(
3494 trait_ref.args.type_at(1),
3495 trait_ref.args.type_at(0),
3496 assume,
3497 ),
3498 Answer::Yes,
3499 );
3500
3501 if is_normalized_yes
3503 && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3504 root_obligation.predicate.kind().skip_binder()
3505 && root_pred.def_id() == trait_predicate.def_id()
3506 {
3507 return (root_obligation.clone(), root_obligation.predicate.kind().rebind(root_pred));
3508 }
3509
3510 (obligation.clone(), trait_predicate)
3511 }
3512
3513 fn get_safe_transmute_error_and_reason(
3514 &self,
3515 obligation: PredicateObligation<'tcx>,
3516 trait_pred: ty::PolyTraitClause<'tcx>,
3517 span: Span,
3518 ) -> GetSafeTransmuteErrorAndReason {
3519 self.probe(|_| {
3520 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
3523 return GetSafeTransmuteErrorAndReason::Default;
3524 }
3525
3526 let trait_pred = self.tcx.erase_and_anonymize_regions(
3528 self.tcx.instantiate_bound_regions_with_erased(trait_pred),
3529 );
3530
3531 let ocx = ObligationCtxt::new(self);
3532 let assume = ocx.normalize(
3533 &obligation.cause,
3534 obligation.param_env,
3535 Unnormalized::new_wip(trait_pred.trait_ref.args.const_at(2)),
3536 );
3537
3538 let Some(assume) = rustc_transmute::Assume::from_const(self.infcx.tcx, assume) else {
3539 self.dcx().span_delayed_bug(
3540 span,
3541 "Unable to construct rustc_transmute::Assume where it was previously possible",
3542 );
3543 return GetSafeTransmuteErrorAndReason::Silent;
3544 };
3545
3546 let dst = trait_pred.trait_ref.args.type_at(0);
3547 let src = trait_pred.trait_ref.args.type_at(1);
3548 let err_msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` cannot be safely transmuted into `{1}`",
src, dst))
})format!("`{src}` cannot be safely transmuted into `{dst}`");
3549
3550 match rustc_transmute::TransmuteTypeEnv::new(self.infcx.tcx)
3551 .is_transmutable(src, dst, assume)
3552 {
3553 Answer::No(reason) => {
3554 let safe_transmute_explanation = match reason {
3555 Reason::SrcIsNotYetSupported => {
3556 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("analyzing the transmutability of `{0}` is not yet supported",
src))
})format!("analyzing the transmutability of `{src}` is not yet supported")
3557 }
3558 Reason::DstIsNotYetSupported => {
3559 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("analyzing the transmutability of `{0}` is not yet supported",
dst))
})format!("analyzing the transmutability of `{dst}` is not yet supported")
3560 }
3561 Reason::DstIsBitIncompatible => {
3562 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("at least one value of `{0}` isn\'t a bit-valid value of `{1}`",
src, dst))
})format!(
3563 "at least one value of `{src}` isn't a bit-valid value of `{dst}`"
3564 )
3565 }
3566 Reason::DstUninhabited => {
3567 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is uninhabited", dst))
})format!("`{dst}` is uninhabited")
3568 }
3569 Reason::DstMayHaveSafetyInvariants => {
3570 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` may carry safety invariants",
dst))
})format!("`{dst}` may carry safety invariants")
3571 }
3572 Reason::DstIsTooBig => {
3573 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the size of `{0}` is smaller than the size of `{1}`",
src, dst))
})format!("the size of `{src}` is smaller than the size of `{dst}`")
3574 }
3575 Reason::DstRefIsTooBig { src, src_size, dst, dst_size } => {
3576 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the size of `{0}` ({1} bytes) is smaller than that of `{2}` ({3} bytes)",
src, src_size, dst, dst_size))
})format!(
3577 "the size of `{src}` ({src_size} bytes) \
3578 is smaller than that of `{dst}` ({dst_size} bytes)"
3579 )
3580 }
3581 Reason::SrcSizeOverflow => {
3582 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
src))
})format!(
3583 "values of the type `{src}` are too big for the target architecture"
3584 )
3585 }
3586 Reason::DstSizeOverflow => {
3587 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
dst))
})format!(
3588 "values of the type `{dst}` are too big for the target architecture"
3589 )
3590 }
3591 Reason::DstHasStricterAlignment { src_min_align, dst_min_align } => {
3592 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the minimum alignment of `{0}` ({1}) should be greater than that of `{2}` ({3})",
src, src_min_align, dst, dst_min_align))
})format!(
3593 "the minimum alignment of `{src}` ({src_min_align}) should be \
3594 greater than that of `{dst}` ({dst_min_align})"
3595 )
3596 }
3597 Reason::DstIsMoreUnique => {
3598 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is a shared reference, but `{1}` is a unique reference",
src, dst))
})format!(
3599 "`{src}` is a shared reference, but `{dst}` is a unique reference"
3600 )
3601 }
3602 Reason::TypeError => {
3604 return GetSafeTransmuteErrorAndReason::Silent;
3605 }
3606 Reason::SrcLayoutUnknown => {
3607 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", src))
})format!("`{src}` has an unknown layout")
3608 }
3609 Reason::DstLayoutUnknown => {
3610 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", dst))
})format!("`{dst}` has an unknown layout")
3611 }
3612 };
3613 GetSafeTransmuteErrorAndReason::Error {
3614 err_msg,
3615 safe_transmute_explanation: Some(safe_transmute_explanation),
3616 }
3617 }
3618 Answer::Yes => ::rustc_span::macros::bug_impl(Some(span),
format_args!("Inconsistent rustc_transmute::is_transmutable(...) result, got Yes"),
Location::caller())span_bug!(
3620 span,
3621 "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
3622 ),
3623 Answer::If(_) => GetSafeTransmuteErrorAndReason::Error {
3628 err_msg,
3629 safe_transmute_explanation: None,
3630 },
3631 }
3632 })
3633 }
3634
3635 fn find_explicit_cast_type(
3638 &self,
3639 param_env: ty::ParamEnv<'tcx>,
3640 found_ty: Ty<'tcx>,
3641 self_ty: Ty<'tcx>,
3642 ) -> Option<Ty<'tcx>> {
3643 let ty::Ref(region, inner_ty, mutbl) = *found_ty.kind() else {
3644 return None;
3645 };
3646
3647 let mut derefs = (self.autoderef_steps)(inner_ty).into_iter();
3648 derefs.next(); let deref_target = derefs.into_iter().next()?.0;
3650
3651 let cast_ty = Ty::new_ref(self.tcx, region, deref_target, mutbl);
3652
3653 let Some(from_def_id) = self.tcx.get_diagnostic_item(sym::From) else {
3654 return None;
3655 };
3656 let Some(try_from_def_id) = self.tcx.get_diagnostic_item(sym::TryFrom) else {
3657 return None;
3658 };
3659
3660 if self.has_impl_for_type(
3661 param_env,
3662 ty::TraitRef::new(
3663 self.tcx,
3664 from_def_id,
3665 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3666 ),
3667 ) {
3668 Some(cast_ty)
3669 } else if self.has_impl_for_type(
3670 param_env,
3671 ty::TraitRef::new(
3672 self.tcx,
3673 try_from_def_id,
3674 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3675 ),
3676 ) {
3677 Some(cast_ty)
3678 } else {
3679 None
3680 }
3681 }
3682
3683 fn has_impl_for_type(
3684 &self,
3685 param_env: ty::ParamEnv<'tcx>,
3686 trait_ref: ty::TraitRef<'tcx>,
3687 ) -> bool {
3688 let obligation = Obligation::new(
3689 self.tcx,
3690 ObligationCause::dummy(),
3691 param_env,
3692 ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Positive },
3693 );
3694
3695 self.predicate_must_hold_modulo_regions(&obligation)
3696 }
3697
3698 fn add_tuple_trait_message(
3699 &self,
3700 obligation_cause_code: &ObligationCauseCode<'tcx>,
3701 err: &mut Diag<'_>,
3702 ) {
3703 match obligation_cause_code {
3704 ObligationCauseCode::RustCall => {
3705 err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
3706 }
3707 ObligationCauseCode::WhereClause(def_id, _) if self.tcx.is_fn_trait(*def_id) => {
3708 err.code(E0059);
3709 err.primary_message(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type parameter to bare `{0}` trait must be a tuple",
self.tcx.def_path_str(*def_id)))
})format!(
3710 "type parameter to bare `{}` trait must be a tuple",
3711 self.tcx.def_path_str(*def_id)
3712 ));
3713 }
3714 _ => {}
3715 }
3716 }
3717
3718 fn try_to_add_help_message(
3719 &self,
3720 root_obligation: &PredicateObligation<'tcx>,
3721 obligation: &PredicateObligation<'tcx>,
3722 trait_predicate: ty::PolyTraitClause<'tcx>,
3723 err: &mut Diag<'_>,
3724 span: Span,
3725 is_fn_trait: bool,
3726 suggested: bool,
3727 ) {
3728 let body_def_id = obligation.cause.body_def_id;
3729 let span = if let ObligationCauseCode::BinOp { rhs_span, .. } = obligation.cause.code() {
3730 *rhs_span
3731 } else {
3732 span
3733 };
3734
3735 let trait_def_id = trait_predicate.def_id();
3737 if is_fn_trait
3738 && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
3739 obligation.param_env,
3740 trait_predicate.self_ty(),
3741 trait_predicate.skip_binder().polarity,
3742 )
3743 {
3744 self.add_help_message_for_fn_trait(trait_predicate, err, implemented_kind, params);
3745 } else if !trait_predicate.has_non_region_infer()
3746 && self.predicate_can_apply(obligation.param_env, trait_predicate)
3747 {
3748 self.suggest_restricting_param_bound(
3756 err,
3757 trait_predicate,
3758 None,
3759 obligation.cause.body_def_id,
3760 );
3761 } else if trait_def_id.is_local()
3762 && self.tcx.trait_impls_of(trait_def_id).is_empty()
3763 && !self.tcx.trait_is_auto(trait_def_id)
3764 && !self.tcx.trait_is_alias(trait_def_id)
3765 && trait_predicate.polarity() == ty::ClausePolarity::Positive
3766 {
3767 err.span_help(
3768 self.tcx.def_span(trait_def_id),
3769 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("this trait has no implementations, consider adding one"))msg!("this trait has no implementations, consider adding one"),
3770 );
3771 } else if !suggested && trait_predicate.polarity() == ty::ClausePolarity::Positive {
3772 let impl_candidates = self.find_similar_impl_candidates(
3774 trait_predicate.def_id(),
3775 trait_predicate.self_ty().skip_binder(),
3776 );
3777 if !self.report_similar_impl_candidates(
3778 &impl_candidates,
3779 obligation,
3780 trait_predicate,
3781 body_def_id,
3782 err,
3783 true,
3784 obligation.param_env,
3785 ) {
3786 self.report_similar_impl_candidates_for_root_obligation(
3787 obligation,
3788 trait_predicate,
3789 body_def_id,
3790 err,
3791 );
3792 }
3793
3794 self.suggest_convert_to_slice(
3795 err,
3796 obligation,
3797 trait_predicate,
3798 impl_candidates.as_slice(),
3799 span,
3800 );
3801
3802 self.suggest_tuple_wrapping(err, root_obligation, obligation);
3803 }
3804 self.suggest_shadowed_inherent_method(err, obligation, trait_predicate);
3805 }
3806
3807 fn add_help_message_for_fn_trait(
3808 &self,
3809 trait_pred: ty::PolyTraitClause<'tcx>,
3810 err: &mut Diag<'_>,
3811 implemented_kind: ty::ClosureKind,
3812 params: ty::Binder<'tcx, Ty<'tcx>>,
3813 ) {
3814 let selected_kind = self
3821 .tcx
3822 .fn_trait_kind_from_def_id(trait_pred.def_id())
3823 .expect("expected to map DefId to ClosureKind");
3824 if !implemented_kind.extends(selected_kind) {
3825 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` implements `{1}`, but it must implement `{2}`, which is more general",
trait_pred.skip_binder().self_ty(), implemented_kind,
selected_kind))
})format!(
3826 "`{}` implements `{}`, but it must implement `{}`, which is more general",
3827 trait_pred.skip_binder().self_ty(),
3828 implemented_kind,
3829 selected_kind
3830 ));
3831 }
3832
3833 let ty::Tuple(given) = *params.skip_binder().kind() else {
3835 return;
3836 };
3837
3838 let expected_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
3839 let ty::Tuple(expected) = *expected_ty.kind() else {
3840 return;
3841 };
3842
3843 if expected.len() != given.len() {
3844 err.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected a closure taking {0} argument{1}, but one taking {2} argument{3} was given",
expected.len(), if expected.len() == 1 { "" } else { "s" },
given.len(), if given.len() == 1 { "" } else { "s" }))
})format!(
3846 "expected a closure taking {} argument{}, but one taking {} argument{} was given",
3847 expected.len(),
3848 pluralize!(expected.len()),
3849 given.len(),
3850 pluralize!(given.len()),
3851 ));
3852 return;
3853 }
3854
3855 let given_ty = Ty::new_fn_ptr(
3856 self.tcx,
3857 params.rebind(self.tcx.mk_fn_sig_safe_rust_abi(given, self.tcx.types.unit)),
3858 );
3859 let expected_ty = Ty::new_fn_ptr(
3860 self.tcx,
3861 trait_pred.rebind(self.tcx.mk_fn_sig_safe_rust_abi(expected, self.tcx.types.unit)),
3862 );
3863
3864 if !self.same_type_modulo_infer(given_ty, expected_ty) {
3865 let (expected_args, given_args) = self.cmp(expected_ty, given_ty);
3867 err.note_expected_found(
3868 "type with signature",
3869 expected_args,
3870 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} with signature",
trait_pred.self_ty().skip_binder().prefix_string(self.tcx)))
})format!(
3871 "{} with signature",
3872 trait_pred.self_ty().skip_binder().prefix_string(self.tcx)
3873 ),
3874 given_args,
3875 );
3876 }
3877 }
3878
3879 fn infer_closure_origin(
3880 &self,
3881 closure_def_id: DefId,
3882 ) -> Option<(Span, rustc_middle::hir::place::Place<'tcx>)> {
3883 let typeck_results = self.typeck_results.as_ref()?;
3884 let local_def_id = closure_def_id.as_local()?;
3885 let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id);
3886 typeck_results.closure_kind_origins().get(hir_id).cloned()
3887 }
3888
3889 fn report_ref_to_fn_once_error(
3890 &self,
3891 closure_def_id: DefId,
3892 trait_prefix: &'static str,
3893 kind_origin: Option<(Span, rustc_middle::hir::place::Place<'tcx>)>,
3894 cause_span: Span,
3895 ) -> Diag<'a> {
3896 let origin = kind_origin.or_else(|| self.infer_closure_origin(closure_def_id));
3897
3898 let err = RefToFnOnce {
3899 cause_span,
3900 trait_prefix,
3901 fn_once_label: origin.map(|(span, place)| ClosureFnOnceLabel {
3902 span,
3903 place: ty::place_to_string_for_capture(self.tcx, &place),
3904 trait_prefix,
3905 }),
3906 };
3907
3908 self.dcx().create_err(err)
3909 }
3910
3911 fn report_closure_error(
3912 &self,
3913 obligation: &PredicateObligation<'tcx>,
3914 closure_def_id: DefId,
3915 found_kind: ty::ClosureKind,
3916 kind: ty::ClosureKind,
3917 trait_prefix: &'static str,
3918 kind_origin: Option<(Span, rustc_middle::hir::place::Place<'tcx>)>,
3919 ) -> Diag<'a> {
3920 let closure_span = self.tcx.def_span(closure_def_id);
3921
3922 let mut err = ClosureKindMismatch {
3923 closure_span,
3924 expected: kind,
3925 found: found_kind,
3926 cause_span: obligation.cause.span,
3927 trait_prefix,
3928 fn_once_label: None,
3929 fn_mut_label: None,
3930 };
3931
3932 let origin = kind_origin.or_else(|| self.infer_closure_origin(closure_def_id));
3935
3936 match (found_kind, origin) {
3937 (ty::ClosureKind::FnOnce, Some((span, place))) => {
3938 err.fn_once_label = Some(ClosureFnOnceLabel {
3939 span,
3940 place: ty::place_to_string_for_capture(self.tcx, &place),
3941 trait_prefix,
3942 })
3943 }
3944 (ty::ClosureKind::FnMut, Some((span, place))) => {
3945 err.fn_mut_label = Some(ClosureFnMutLabel {
3946 span,
3947 place: ty::place_to_string_for_capture(self.tcx, &place),
3948 trait_prefix,
3949 })
3950 }
3951 _ => {}
3952 }
3953
3954 self.dcx().create_err(err)
3955 }
3956
3957 fn report_cyclic_signature_error(
3958 &self,
3959 obligation: &PredicateObligation<'tcx>,
3960 found_trait_ref: ty::TraitRef<'tcx>,
3961 expected_trait_ref: ty::TraitRef<'tcx>,
3962 terr: TypeError<'tcx>,
3963 ) -> Diag<'a> {
3964 let self_ty = found_trait_ref.self_ty();
3965 let (cause, terr) = if let ty::Closure(def_id, _) = *self_ty.kind() {
3966 (
3967 ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
3968 TypeError::CyclicTy(self_ty),
3969 )
3970 } else {
3971 (obligation.cause.clone(), terr)
3972 };
3973 self.report_and_explain_type_error(
3974 TypeTrace::trait_refs(&cause, expected_trait_ref, found_trait_ref),
3975 obligation.param_env,
3976 terr,
3977 )
3978 }
3979
3980 fn report_signature_mismatch_error(
3981 &self,
3982 obligation: &PredicateObligation<'tcx>,
3983 span: Span,
3984 found_trait_ref: ty::TraitRef<'tcx>,
3985 expected_trait_ref: ty::TraitRef<'tcx>,
3986 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3987 let found_trait_ref = self.deeply_resolve_ignoring_regions(found_trait_ref);
3988 let expected_trait_ref = self.deeply_resolve_ignoring_regions(expected_trait_ref);
3989
3990 expected_trait_ref.self_ty().error_reported()?;
3991 let found_trait_ty = found_trait_ref.self_ty();
3992
3993 let found_did = match *found_trait_ty.kind() {
3994 ty::Closure(did, _) | ty::FnDef(did, _) | ty::Coroutine(did, ..) => Some(did),
3995 _ => None,
3996 };
3997
3998 let found_node = found_did.and_then(|did| self.tcx.hir_get_if_local(did));
3999 let found_span = found_did.and_then(|did| self.tcx.hir_span_if_local(did));
4000
4001 if !self.reported_signature_mismatch.borrow_mut().insert((span, found_span)) {
4002 return Err(self.dcx().span_delayed_bug(span, "already_reported"));
4005 }
4006
4007 let mut not_tupled = false;
4008
4009 let found = match found_trait_ref.args.type_at(1).kind() {
4010 ty::Tuple(tys) => ::alloc::vec::from_elem_global(ArgKind::empty(), tys.len())vec![ArgKind::empty(); tys.len()],
4011 _ => {
4012 not_tupled = true;
4013 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ArgKind::empty()]))vec![ArgKind::empty()]
4014 }
4015 };
4016
4017 let expected_ty = expected_trait_ref.args.type_at(1);
4018 let expected = match expected_ty.kind() {
4019 ty::Tuple(tys) => {
4020 tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
4021 }
4022 _ => {
4023 not_tupled = true;
4024 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ArgKind::Arg("_".to_owned(), expected_ty.to_string())]))vec![ArgKind::Arg("_".to_owned(), expected_ty.to_string())]
4025 }
4026 };
4027
4028 if !self.tcx.is_lang_item(expected_trait_ref.def_id, LangItem::Coroutine) && not_tupled {
4034 return Ok(self.report_and_explain_type_error(
4035 TypeTrace::trait_refs(&obligation.cause, expected_trait_ref, found_trait_ref),
4036 obligation.param_env,
4037 ty::error::TypeError::Mismatch,
4038 ));
4039 }
4040 if found.len() != expected.len() {
4041 let (closure_span, closure_arg_span, found) = found_did
4042 .and_then(|did| {
4043 let node = self.tcx.hir_get_if_local(did)?;
4044 let (found_span, closure_arg_span, found) = self.get_fn_like_arguments(node)?;
4045 Some((Some(found_span), closure_arg_span, found))
4046 })
4047 .unwrap_or((found_span, None, found));
4048
4049 if found.len() != expected.len() {
4055 return Ok(self.report_arg_count_mismatch(
4056 span,
4057 closure_span,
4058 expected,
4059 found,
4060 found_trait_ty.is_closure(),
4061 closure_arg_span,
4062 ));
4063 }
4064 }
4065 Ok(self.report_closure_arg_mismatch(
4066 span,
4067 found_span,
4068 found_trait_ref,
4069 expected_trait_ref,
4070 obligation.cause.code(),
4071 found_node,
4072 obligation.param_env,
4073 ))
4074 }
4075
4076 pub fn get_fn_like_arguments(
4081 &self,
4082 node: Node<'_>,
4083 ) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
4084 let sm = self.tcx.sess.source_map();
4085 Some(match node {
4086 Node::Expr(&hir::Expr {
4087 kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
4088 ..
4089 }) => (
4090 fn_decl_span,
4091 fn_arg_span,
4092 self.tcx
4093 .hir_body(body)
4094 .params
4095 .iter()
4096 .map(|arg| {
4097 if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat
4098 {
4099 Some(ArgKind::Tuple(
4100 Some(span),
4101 args.iter()
4102 .map(|pat| {
4103 sm.span_to_snippet(pat.span)
4104 .ok()
4105 .map(|snippet| (snippet, "_".to_owned()))
4106 })
4107 .collect::<Option<Vec<_>>>()?,
4108 ))
4109 } else {
4110 let name = sm.span_to_snippet(arg.pat.span).ok()?;
4111 Some(ArgKind::Arg(name, "_".to_owned()))
4112 }
4113 })
4114 .collect::<Option<Vec<ArgKind>>>()?,
4115 ),
4116 Node::Item(&hir::Item { kind: hir::ItemKind::Fn { ref sig, .. }, .. })
4117 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
4118 | Node::TraitItem(&hir::TraitItem {
4119 kind: hir::TraitItemKind::Fn(ref sig, _), ..
4120 })
4121 | Node::ForeignItem(&hir::ForeignItem {
4122 kind: hir::ForeignItemKind::Fn(ref sig, _, _),
4123 ..
4124 }) => (
4125 sig.span,
4126 None,
4127 sig.decl
4128 .inputs
4129 .iter()
4130 .map(|arg| match arg.kind {
4131 hir::TyKind::Tup(tys) => ArgKind::Tuple(
4132 Some(arg.span),
4133 ::alloc::vec::from_elem_global(("_".to_owned(), "_".to_owned()), tys.len())vec![("_".to_owned(), "_".to_owned()); tys.len()],
4134 ),
4135 _ => ArgKind::empty(),
4136 })
4137 .collect::<Vec<ArgKind>>(),
4138 ),
4139 Node::Ctor(variant_data) => {
4140 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| self.tcx.hir_span(id));
4141 (span, None, ::alloc::vec::from_elem_global(ArgKind::empty(), variant_data.fields().len())vec![ArgKind::empty(); variant_data.fields().len()])
4142 }
4143 _ => {
::core::panicking::panic_fmt(format_args!("non-FnLike node found: {0:?}",
node));
}panic!("non-FnLike node found: {node:?}"),
4144 })
4145 }
4146
4147 pub fn report_arg_count_mismatch(
4151 &self,
4152 span: Span,
4153 found_span: Option<Span>,
4154 expected_args: Vec<ArgKind>,
4155 found_args: Vec<ArgKind>,
4156 is_closure: bool,
4157 closure_arg_span: Option<Span>,
4158 ) -> Diag<'a> {
4159 let kind = if is_closure { "closure" } else { "function" };
4160
4161 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
4162 let arg_length = arguments.len();
4163 let distinct = #[allow(non_exhaustive_omitted_patterns)] match other {
&[ArgKind::Tuple(..)] => true,
_ => false,
}matches!(other, &[ArgKind::Tuple(..)]);
4164 match (arg_length, arguments.get(0)) {
4165 (1, Some(ArgKind::Tuple(_, fields))) => {
4166 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("a single {0}-tuple as argument",
fields.len()))
})format!("a single {}-tuple as argument", fields.len())
4167 }
4168 _ => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}argument{2}", arg_length,
if distinct && arg_length > 1 { "distinct " } else { "" },
if arg_length == 1 { "" } else { "s" }))
})format!(
4169 "{} {}argument{}",
4170 arg_length,
4171 if distinct && arg_length > 1 { "distinct " } else { "" },
4172 pluralize!(arg_length)
4173 ),
4174 }
4175 };
4176
4177 let expected_str = args_str(&expected_args, &found_args);
4178 let found_str = args_str(&found_args, &expected_args);
4179
4180 let mut err = {
self.dcx().struct_span_err(span,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is expected to take {1}, but it takes {2}",
kind, expected_str, found_str))
})).with_code(E0593)
}struct_span_code_err!(
4181 self.dcx(),
4182 span,
4183 E0593,
4184 "{} is expected to take {}, but it takes {}",
4185 kind,
4186 expected_str,
4187 found_str,
4188 );
4189
4190 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0} that takes {1}", kind,
expected_str))
})format!("expected {kind} that takes {expected_str}"));
4191
4192 if let Some(found_span) = found_span {
4193 err.span_label(found_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("takes {0}", found_str))
})format!("takes {found_str}"));
4194
4195 if found_args.is_empty() && is_closure {
4199 let underscores = ::alloc::vec::from_elem_global("_", expected_args.len())vec!["_"; expected_args.len()].join(", ");
4200 err.span_suggestion_verbose(
4201 closure_arg_span.unwrap_or(found_span),
4202 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("consider changing the closure to take and ignore the expected argument{0}",
if expected_args.len() == 1 { "" } else { "s" }))
})format!(
4203 "consider changing the closure to take and ignore the expected argument{}",
4204 pluralize!(expected_args.len())
4205 ),
4206 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", underscores))
})format!("|{underscores}|"),
4207 Applicability::MachineApplicable,
4208 );
4209 }
4210
4211 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
4212 if fields.len() == expected_args.len() {
4213 let sugg = fields
4214 .iter()
4215 .map(|(name, _)| name.to_owned())
4216 .collect::<Vec<String>>()
4217 .join(", ");
4218 err.span_suggestion_verbose(
4219 found_span,
4220 "change the closure to take multiple arguments instead of a single tuple",
4221 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", sugg))
})format!("|{sugg}|"),
4222 Applicability::MachineApplicable,
4223 );
4224 }
4225 }
4226 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
4227 && fields.len() == found_args.len()
4228 && is_closure
4229 {
4230 let sugg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|({0}){1}|",
found_args.iter().map(|arg|
match arg {
ArgKind::Arg(name, _) => name.to_owned(),
_ => "_".to_owned(),
}).collect::<Vec<String>>().join(", "),
if found_args.iter().any(|arg|
match arg { ArgKind::Arg(_, ty) => ty != "_", _ => false, })
{
::alloc::__export::must_use({
::alloc::fmt::format(format_args!(": ({0})",
fields.iter().map(|(_, ty)|
ty.to_owned()).collect::<Vec<String>>().join(", ")))
})
} else { String::new() }))
})format!(
4231 "|({}){}|",
4232 found_args
4233 .iter()
4234 .map(|arg| match arg {
4235 ArgKind::Arg(name, _) => name.to_owned(),
4236 _ => "_".to_owned(),
4237 })
4238 .collect::<Vec<String>>()
4239 .join(", "),
4240 if found_args.iter().any(|arg| match arg {
4242 ArgKind::Arg(_, ty) => ty != "_",
4243 _ => false,
4244 }) {
4245 format!(
4246 ": ({})",
4247 fields
4248 .iter()
4249 .map(|(_, ty)| ty.to_owned())
4250 .collect::<Vec<String>>()
4251 .join(", ")
4252 )
4253 } else {
4254 String::new()
4255 },
4256 );
4257 err.span_suggestion_verbose(
4258 found_span,
4259 "change the closure to accept a tuple instead of individual arguments",
4260 sugg,
4261 Applicability::MachineApplicable,
4262 );
4263 }
4264 }
4265
4266 err
4267 }
4268
4269 pub fn type_implements_fn_trait(
4273 &self,
4274 param_env: ty::ParamEnv<'tcx>,
4275 ty: ty::Binder<'tcx, Ty<'tcx>>,
4276 polarity: ty::ClausePolarity,
4277 ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
4278 self.commit_if_ok(|_| {
4279 for trait_def_id in [
4280 self.tcx.lang_items().fn_trait(),
4281 self.tcx.lang_items().fn_mut_trait(),
4282 self.tcx.lang_items().fn_once_trait(),
4283 ] {
4284 let Some(trait_def_id) = trait_def_id else { continue };
4285 let var = self.next_ty_var(DUMMY_SP);
4288 let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
4290 let obligation = Obligation::new(
4291 self.tcx,
4292 ObligationCause::dummy(),
4293 param_env,
4294 ty.rebind(ty::TraitClause { trait_ref, polarity }),
4295 );
4296 let ocx = ObligationCtxt::new(self);
4297 ocx.register_obligation(obligation);
4298 if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
4299 return Ok((
4300 self.tcx
4301 .fn_trait_kind_from_def_id(trait_def_id)
4302 .expect("expected to map DefId to ClosureKind"),
4303 ty.rebind(self.deeply_resolve_ignoring_regions(var)),
4304 ));
4305 }
4306 }
4307
4308 Err(())
4309 })
4310 }
4311
4312 fn report_not_const_evaluatable_error(
4313 &self,
4314 obligation: &PredicateObligation<'tcx>,
4315 span: Span,
4316 ) -> Result<Diag<'a>, ErrorGuaranteed> {
4317 if !self.tcx.features().generic_const_exprs() && !self.tcx.features().gca() {
4318 let guar = self
4319 .dcx()
4320 .struct_span_err(span, "constant expression depends on a generic parameter")
4321 .with_note("this may fail depending on what value the parameter takes")
4328 .emit_err();
4329 return Err(guar);
4330 }
4331
4332 match obligation.predicate.kind().skip_binder() {
4333 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => match ct.kind() {
4334 ty::ConstKind::Alias(_, alias_const) => {
4335 let mut err =
4336 self.dcx().struct_span_err(span, "unconstrained generic constant");
4337
4338 let const_span = alias_const.kind.def_span(self.tcx);
4339 let const_ty = alias_const.type_of(self.tcx).skip_norm_wip();
4340
4341 let msg = "try adding a `where` bound";
4342 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(const_span) {
4343 let code = if const_ty == self.tcx.types.usize {
4344 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); {0}]:", snippet))
})format!("[(); {snippet}]:")
4345 } else if let ty::AliasConstKind::Anon { def_id } = alias_const.kind
4346 && let Some(local_def_id) = def_id.as_local()
4347 && let Some(local_body) = self.tcx.hir_maybe_body_owned_by(local_def_id)
4348 && expr_needs_parens(local_body.value)
4349 {
4350 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); ({0}) as usize]:", snippet))
})format!("[(); ({snippet}) as usize]:")
4351 } else {
4352 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); {0} as usize]:", snippet))
})format!("[(); {snippet} as usize]:")
4353 };
4354
4355 let suggestion_def_id = if let ObligationCauseCode::CompareImplItem {
4356 trait_item_def_id,
4357 ..
4358 } = obligation.cause.code()
4359 {
4360 trait_item_def_id.as_local()
4361 } else {
4362 Some(obligation.cause.body_def_id)
4363 };
4364
4365 if let Some(suggestion_def_id) = suggestion_def_id
4366 && let Some(generics) = self.tcx.hir_get_generics(suggestion_def_id)
4367 {
4368 err.span_suggestion_verbose(
4369 generics.tail_span_for_predicate_suggestion(),
4370 msg,
4371 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}",
generics.add_where_or_trailing_comma(), code))
})format!("{} {code}", generics.add_where_or_trailing_comma()),
4372 Applicability::MaybeIncorrect,
4373 );
4374 } else {
4375 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: where {1}", msg, code))
})format!("{msg}: where {code}"));
4376 };
4377 } else {
4378 err.help(msg);
4379 }
4380 Ok(err)
4381 }
4382 ty::ConstKind::Expr(_) => {
4383 let err = self
4384 .dcx()
4385 .struct_span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unconstrained generic constant `{0}`",
ct))
})format!("unconstrained generic constant `{ct}`"));
4386 Ok(err)
4387 }
4388 _ => {
4389 ::rustc_span::macros::bug_impl(None,
format_args!("const evaluatable failed for non-alias const `{0:?}`", ct),
Location::caller());bug!("const evaluatable failed for non-alias const `{ct:?}`");
4390 }
4391 },
4392 _ => {
4393 ::rustc_span::macros::bug_impl(Some(span),
format_args!("unexpected non-ConstEvaluatable predicate, this should not be reachable"),
Location::caller())span_bug!(
4394 span,
4395 "unexpected non-ConstEvaluatable predicate, this should not be reachable"
4396 )
4397 }
4398 }
4399 }
4400}