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_data_structures::fx::{FxHashMap, FxHashSet};
10use rustc_data_structures::unord::UnordSet;
11use rustc_errors::codes::*;
12use rustc_errors::{
13 Applicability, Diag, ErrorGuaranteed, Level, MultiSpan, StashKey, StringPart, Suggestions, msg,
14 pluralize, struct_span_code_err,
15};
16use rustc_hir::attrs::diagnostic::CustomDiagnostic;
17use rustc_hir::attrs::lang_items::LangItem;
18use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
19use rustc_hir::intravisit::Visitor;
20use rustc_hir::{self as hir, Node, expr_needs_parens, find_attr};
21use rustc_infer::infer::{InferOk, TypeTrace};
22use rustc_infer::traits::solve::Goal;
23use rustc_infer::traits::{ImplSource, TraitErrors};
24use rustc_middle::traits::SignatureMismatchData;
25use rustc_middle::traits::select::OverflowError;
26use rustc_middle::ty::abstract_const::NotConstEvaluatable;
27use rustc_middle::ty::error::{ExpectedFound, TypeError};
28use rustc_middle::ty::print::{
29 PrintPolyTraitPredicateExt, PrintPolyTraitRefExt as _, PrintTraitPredicateExt as _,
30 PrintTraitRefExt as _, with_forced_trimmed_paths,
31};
32use rustc_middle::ty::{
33 self, GenericArgKind, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeFoldable, TypeFolder,
34 TypeSuperFoldable, TypeVisitableExt, Unnormalized, Upcast,
35};
36use rustc_middle::{bug, span_bug};
37use rustc_span::def_id::CrateNum;
38use rustc_span::{BytePos, DUMMY_SP, STDLIB_STABLE_CRATES, Span, Symbol, sym};
39use tracing::{debug, instrument};
40
41use super::suggestions::get_explanation_based_on_obligation;
42use super::{ArgKind, CandidateSimilarity, GetSafeTransmuteErrorAndReason, ImplCandidate};
43use crate::diagnostics::{
44 ClosureFnMutLabel, ClosureFnOnceLabel, ClosureKindMismatch, CoroClosureNotFn,
45};
46use crate::error_reporting::TypeErrCtxt;
47use crate::error_reporting::infer::TyCategory;
48use crate::error_reporting::traits::report_dyn_incompatibility;
49use crate::infer::{self, InferCtxt, InferCtxtExt as _};
50use crate::traits::query::evaluate_obligation::InferCtxtExt as _;
51use crate::traits::{
52 MismatchedProjectionTypes, NormalizeExt, Obligation, ObligationCause, ObligationCauseCode,
53 ObligationCtxt, PredicateObligation, SelectionContext, SelectionError, elaborate,
54 specialization_graph,
55};
56
57impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
58 pub fn report_selection_error(
62 &self,
63 mut obligation: PredicateObligation<'tcx>,
64 root_obligation: &PredicateObligation<'tcx>,
65 error: &SelectionError<'tcx>,
66 ) -> ErrorGuaranteed {
67 let tcx = self.tcx;
68 let mut span = obligation.cause.span;
69 let mut long_ty_file = None;
70
71 let mut err = match *error {
72 SelectionError::Unimplemented => {
73 if let ObligationCauseCode::WellFormed(Some(wf_loc)) =
76 root_obligation.cause.code().peel_derives()
77 && !obligation.predicate.has_non_region_infer()
78 {
79 if let Some(cause) = self.tcx.diagnostic_hir_wf_check((
80 tcx.erase_and_anonymize_regions(obligation.predicate),
81 *wf_loc,
82 )) {
83 obligation.cause = cause.clone();
84 span = obligation.cause.span;
85 }
86 }
87
88 if let ObligationCauseCode::CompareImplItem {
89 impl_item_def_id,
90 trait_item_def_id,
91 kind: _,
92 } = *obligation.cause.code()
93 {
94 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs:94",
"rustc_trait_selection::error_reporting::traits::fulfillment_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
::tracing_core::__macro_support::Option::Some(94u32),
::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");
95 return self
96 .report_extra_impl_obligation(
97 span,
98 impl_item_def_id,
99 trait_item_def_id,
100 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`", obligation.predicate))
})format!("`{}`", obligation.predicate),
101 )
102 .emit();
103 }
104
105 if let ObligationCauseCode::ConstParam(ty) = *obligation.cause.code().peel_derives()
107 {
108 return self.report_const_param_not_wf(ty, &obligation).emit();
109 }
110
111 let bound_predicate = obligation.predicate.kind();
112 match bound_predicate.skip_binder() {
113 ty::PredicateKind::Clause(ty::ClauseKind::Trait(trait_predicate)) => {
114 let leaf_trait_predicate =
115 self.resolve_vars_if_possible(bound_predicate.rebind(trait_predicate));
116
117 let (main_trait_predicate, main_obligation) =
124 if let ty::PredicateKind::Clause(
125 ty::ClauseKind::Trait(root_pred)
126 ) = root_obligation.predicate.kind().skip_binder()
127 && !leaf_trait_predicate.self_ty().skip_binder().has_escaping_bound_vars()
128 && !root_pred.self_ty().has_escaping_bound_vars()
129 && (
134 self.can_eq(
136 obligation.param_env,
137 leaf_trait_predicate.self_ty().skip_binder(),
138 root_pred.self_ty().peel_refs(),
139 )
140 || self.can_eq(
142 obligation.param_env,
143 leaf_trait_predicate.self_ty().skip_binder(),
144 root_pred.self_ty(),
145 )
146 )
147 && leaf_trait_predicate.def_id() != root_pred.def_id()
151 && !self.tcx.is_lang_item(root_pred.def_id(), LangItem::Unsize)
154 {
155 (
156 self.resolve_vars_if_possible(
157 root_obligation.predicate.kind().rebind(root_pred),
158 ),
159 root_obligation,
160 )
161 } else {
162 (leaf_trait_predicate, &obligation)
163 };
164
165 if let Some(guar) = self
166 .emit_specialized_closure_kind_error(&obligation, leaf_trait_predicate)
167 {
168 return guar;
169 }
170
171 if let Err(guar) = leaf_trait_predicate.error_reported() {
172 return guar;
173 }
174 if let Err(guar) = self.fn_arg_obligation(&obligation) {
177 return guar;
178 }
179 let (post_message, pre_message, type_def) = self
180 .get_parent_trait_ref(obligation.cause.code())
181 .map(|(t, s)| {
182 let t = self.tcx.short_string(t, &mut long_ty_file);
183 (
184 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" in `{0}`", t))
})format!(" in `{t}`"),
185 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("within `{0}`, ", t))
})format!("within `{t}`, "),
186 s.map(|s| (::alloc::__export::must_use({
::alloc::fmt::format(format_args!("within this `{0}`", t))
})format!("within this `{t}`"), s)),
187 )
188 })
189 .unwrap_or_default();
190
191 let CustomDiagnostic { message, label, notes, parent_label } = self
192 .on_unimplemented_note(
193 main_trait_predicate,
194 main_obligation,
195 &mut long_ty_file,
196 );
197
198 let have_alt_message = message.is_some() || label.is_some();
199
200 let message = message.unwrap_or_else(|| {
201 self.get_standard_error_message(
202 main_trait_predicate,
203 None,
204 post_message,
205 &mut long_ty_file,
206 )
207 });
208 let is_try_conversion =
209 self.is_try_conversion(span, main_trait_predicate.def_id());
210 let is_question_mark = #[allow(non_exhaustive_omitted_patterns)] match root_obligation.cause.code().peel_derives()
{
ObligationCauseCode::QuestionMark => true,
_ => false,
}matches!(
211 root_obligation.cause.code().peel_derives(),
212 ObligationCauseCode::QuestionMark,
213 ) && !(self
214 .tcx
215 .is_diagnostic_item(sym::FromResidual, main_trait_predicate.def_id())
216 || self.tcx.is_lang_item(main_trait_predicate.def_id(), LangItem::Try));
217 let is_unsize =
218 self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Unsize);
219 let question_mark_message = "the question mark operation (`?`) implicitly \
220 performs a conversion on the error value \
221 using the `From` trait";
222 let (message, notes) = if is_try_conversion {
223 let ty = self.tcx.short_string(
224 main_trait_predicate.skip_binder().self_ty(),
225 &mut long_ty_file,
226 );
227 (
229 ::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}`"),
230 ::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()],
231 )
232 } else if is_question_mark {
233 let main_trait_predicate =
234 self.tcx.short_string(main_trait_predicate, &mut long_ty_file);
235 (
239 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`?` couldn\'t convert the error: `{0}` is not satisfied",
main_trait_predicate))
})format!(
240 "`?` couldn't convert the error: `{main_trait_predicate}` is \
241 not satisfied",
242 ),
243 ::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()],
244 )
245 } else {
246 (message, notes)
247 };
248
249 let (err_msg, safe_transmute_explanation) = if self
250 .tcx
251 .is_lang_item(main_trait_predicate.def_id(), LangItem::TransmuteTrait)
252 {
253 let (report_obligation, report_pred) = self
255 .select_transmute_obligation_for_reporting(
256 &obligation,
257 main_trait_predicate,
258 root_obligation,
259 );
260
261 match self.get_safe_transmute_error_and_reason(
262 report_obligation,
263 report_pred,
264 span,
265 ) {
266 GetSafeTransmuteErrorAndReason::Silent => {
267 return self
268 .dcx()
269 .span_delayed_bug(span, "silent safe transmute error");
270 }
271 GetSafeTransmuteErrorAndReason::Default => (message, None),
272 GetSafeTransmuteErrorAndReason::Error {
273 err_msg,
274 safe_transmute_explanation,
275 } => (err_msg, safe_transmute_explanation),
276 }
277 } else {
278 (message, None)
279 };
280
281 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);
282
283 let trait_def_id = main_trait_predicate.def_id();
284 let leaf_trait_def_id = leaf_trait_predicate.def_id();
285 if (self.tcx.is_diagnostic_item(sym::From, trait_def_id)
286 || self.tcx.is_diagnostic_item(sym::TryFrom, trait_def_id))
287 && (self.tcx.is_diagnostic_item(sym::From, leaf_trait_def_id)
288 || self.tcx.is_diagnostic_item(sym::TryFrom, leaf_trait_def_id))
289 && let Some(trait_ref) =
290 leaf_trait_predicate.no_bound_vars().map(|pred| pred.trait_ref)
291 && let Some(found_ty) =
292 trait_ref.args.get(1).and_then(|arg| arg.as_type())
293 && let Some(ty) =
294 main_trait_predicate.no_bound_vars().map(|pred| pred.self_ty())
295 && let Some(cast_ty) =
296 self.find_explicit_cast_type(obligation.param_env, found_ty, ty)
297 {
298 let found_ty_str = self.tcx.short_string(found_ty, &mut long_ty_file);
299 let cast_ty_str = self.tcx.short_string(cast_ty, &mut long_ty_file);
300
301 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!(
302 "consider casting the `{found_ty_str}` value to `{cast_ty_str}`",
303 ));
304 }
305
306 *err.long_ty_path() = long_ty_file;
307
308 let mut suggested = false;
309 let mut noted_missing_impl = false;
310 if is_try_conversion || is_question_mark {
311 (suggested, noted_missing_impl) = self.try_conversion_context(
312 &obligation,
313 main_trait_predicate,
314 &mut err,
315 );
316 }
317
318 suggested |= self.detect_negative_literal(
319 &obligation,
320 main_trait_predicate,
321 &mut err,
322 );
323
324 if let Some(ret_span) = self.return_type_span(&obligation) {
325 if is_try_conversion {
326 let ty = self.tcx.short_string(
327 main_trait_predicate.skip_binder().self_ty(),
328 err.long_ty_path(),
329 );
330 err.span_label(
331 ret_span,
332 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected `{0}` because of this",
ty))
})format!("expected `{ty}` because of this"),
333 );
334 } else if is_question_mark {
335 let main_trait_predicate =
336 self.tcx.short_string(main_trait_predicate, err.long_ty_path());
337 err.span_label(
338 ret_span,
339 ::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"),
340 );
341 }
342 }
343
344 if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Tuple) {
345 self.add_tuple_trait_message(
346 obligation.cause.code().peel_derives(),
347 &mut err,
348 );
349 }
350
351 let explanation = get_explanation_based_on_obligation(
352 self.tcx,
353 &obligation,
354 leaf_trait_predicate,
355 pre_message,
356 err.long_ty_path(),
357 );
358
359 self.check_for_binding_assigned_block_without_tail_expression(
360 &obligation,
361 &mut err,
362 leaf_trait_predicate,
363 );
364 self.suggest_add_result_as_return_type(
365 &obligation,
366 &mut err,
367 leaf_trait_predicate,
368 );
369
370 if self.suggest_add_reference_to_arg(
371 &obligation,
372 &mut err,
373 leaf_trait_predicate,
374 have_alt_message,
375 ) {
376 self.note_obligation_cause(&mut err, &obligation);
377 return err.emit();
378 }
379
380 let ty_span = match leaf_trait_predicate.self_ty().skip_binder().kind() {
381 ty::Adt(def, _)
382 if def.did().is_local()
383 && !self
384 .can_suggest_derive(&obligation, leaf_trait_predicate) =>
385 {
386 self.tcx.def_span(def.did())
387 }
388 _ => DUMMY_SP,
389 };
390 if let Some(s) = label {
391 err.span_label(span, s);
394 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(_))
395 && !self.tcx.is_diagnostic_item(sym::FromResidual, leaf_trait_predicate.def_id())
399 {
402 if ty_span == DUMMY_SP {
405 err.help(explanation);
406 } else {
407 err.span_help(ty_span, explanation);
408 }
409 }
410 } else if let Some(custom_explanation) = safe_transmute_explanation {
411 err.span_label(span, custom_explanation);
412 } else if (explanation.len() > self.tcx.sess.diagnostic_width()
413 || ty_span != DUMMY_SP)
414 && !noted_missing_impl
415 {
416 err.span_label(span, "unsatisfied trait bound");
419
420 if ty_span == DUMMY_SP {
423 err.help(explanation);
424 } else {
425 err.span_help(ty_span, explanation);
426 }
427 } else {
428 err.span_label(span, explanation);
429 }
430
431 if let ObligationCauseCode::Coercion { source, target } =
432 *obligation.cause.code().peel_derives()
433 {
434 if self.tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Sized)
435 {
436 self.suggest_borrowing_for_object_cast(
437 &mut err,
438 root_obligation,
439 source,
440 target,
441 );
442 }
443 }
444
445 if let Some((msg, span)) = type_def {
446 err.span_label(span, msg);
447 }
448 let derive_suggestion_will_be_shown = main_trait_predicate
456 == leaf_trait_predicate
457 && self.can_suggest_derive(&obligation, leaf_trait_predicate);
458 if !derive_suggestion_will_be_shown {
459 for note in notes {
460 err.note(note);
463 }
464 }
465 if let Some(s) = parent_label {
466 let body = obligation.cause.body_def_id;
467 err.span_label(tcx.def_span(body), s);
468 }
469
470 self.suggest_floating_point_literal(
471 &obligation,
472 &mut err,
473 leaf_trait_predicate,
474 );
475 self.suggest_dereferencing_index(
476 &obligation,
477 &mut err,
478 leaf_trait_predicate,
479 );
480 suggested |=
481 self.suggest_dereferences(&obligation, &mut err, leaf_trait_predicate);
482 suggested |=
483 self.suggest_fn_call(&obligation, &mut err, leaf_trait_predicate);
484 suggested |= self.suggest_cast_to_fn_pointer(
485 &obligation,
486 &mut err,
487 leaf_trait_predicate,
488 main_trait_predicate,
489 span,
490 );
491 suggested |= self.suggest_remove_reference(
492 &obligation,
493 &mut err,
494 leaf_trait_predicate,
495 );
496 suggested |= self.suggest_semicolon_removal(
497 &obligation,
498 &mut err,
499 span,
500 leaf_trait_predicate,
501 );
502 self.note_different_trait_with_same_name(
503 &mut err,
504 &obligation,
505 leaf_trait_predicate,
506 );
507 self.note_adt_version_mismatch(&mut err, leaf_trait_predicate);
508 self.suggest_remove_await(&obligation, &mut err);
509 self.suggest_derive(&obligation, &mut err, leaf_trait_predicate);
510
511 if tcx.is_lang_item(leaf_trait_predicate.def_id(), LangItem::Try) {
512 self.suggest_await_before_try(
513 &mut err,
514 &obligation,
515 leaf_trait_predicate,
516 span,
517 );
518 }
519
520 if self.suggest_add_clone_to_arg(
521 &obligation,
522 &mut err,
523 leaf_trait_predicate,
524 ) {
525 return err.emit();
526 }
527
528 if self.suggest_impl_trait(&mut err, &obligation, leaf_trait_predicate) {
529 return err.emit();
530 }
531
532 if is_unsize {
533 err.note(
536 "all implementations of `Unsize` are provided \
537 automatically by the compiler, see \
538 <https://doc.rust-lang.org/stable/std/marker/trait.Unsize.html> \
539 for more information",
540 );
541 }
542
543 let is_fn_trait = tcx.is_fn_trait(leaf_trait_predicate.def_id());
544 let is_target_feature_fn = if let ty::FnDef(def_id, _) =
545 *leaf_trait_predicate.skip_binder().self_ty().kind()
546 {
547 !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
548 } else {
549 false
550 };
551 if is_fn_trait && is_target_feature_fn {
552 err.note(
553 "`#[target_feature(..)]` functions do not implement the `Fn` traits",
554 );
555 err.note(
556 "try casting the function to a `fn` pointer or wrapping it in a closure",
557 );
558 }
559
560 self.note_field_shadowed_by_private_candidate_in_cause(
561 &mut err,
562 &obligation.cause,
563 obligation.param_env,
564 );
565 self.try_to_add_help_message(
566 &root_obligation,
567 &obligation,
568 leaf_trait_predicate,
569 &mut err,
570 span,
571 is_fn_trait,
572 suggested,
573 );
574
575 if !is_unsize {
578 self.suggest_change_mut(&obligation, &mut err, leaf_trait_predicate);
579 }
580
581 if leaf_trait_predicate.skip_binder().self_ty().is_never()
586 && self.diverging_fallback_has_occurred
587 {
588 let predicate = leaf_trait_predicate.map_bound(|trait_pred| {
589 trait_pred.with_replaced_self_ty(self.tcx, tcx.types.unit)
590 });
591 let unit_obligation = obligation.with(tcx, predicate);
592 if self.predicate_may_hold(&unit_obligation) {
593 err.note(
594 "this error might have been caused by changes to \
595 Rust's type-inference algorithm (see issue #148922 \
596 <https://github.com/rust-lang/rust/issues/148922> \
597 for more information)",
598 );
599 err.help(
600 "you might have intended to use the type `()` here instead",
601 );
602 }
603 }
604
605 self.explain_hrtb_projection(
606 &mut err,
607 leaf_trait_predicate,
608 obligation.param_env,
609 &obligation.cause,
610 );
611 self.suggest_desugaring_async_fn_in_trait(&mut err, main_trait_predicate);
612
613 let in_std_macro =
619 match obligation.cause.span.ctxt().outer_expn_data().macro_def_id {
620 Some(macro_def_id) => {
621 let crate_name = tcx.crate_name(macro_def_id.krate);
622 STDLIB_STABLE_CRATES.contains(&crate_name)
623 }
624 None => false,
625 };
626
627 if in_std_macro
628 && #[allow(non_exhaustive_omitted_patterns)] match self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id())
{
Some(sym::Debug | sym::Display) => true,
_ => false,
}matches!(
629 self.tcx.get_diagnostic_name(leaf_trait_predicate.def_id()),
630 Some(sym::Debug | sym::Display)
631 )
632 {
633 return err.emit();
634 }
635
636 err
637 }
638
639 ty::PredicateKind::Clause(ty::ClauseKind::HostEffect(clause)) => self
640 .report_host_effect_error(
641 bound_predicate.rebind(clause),
642 &obligation,
643 span,
644 ),
645
646 ty::PredicateKind::Subtype(predicate) => {
647 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("subtype requirement gave wrong error: `{0:?}`", predicate))span_bug!(span, "subtype requirement gave wrong error: `{:?}`", predicate)
651 }
652
653 ty::PredicateKind::Coerce(predicate) => {
654 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("coerce requirement gave wrong error: `{0:?}`", predicate))span_bug!(span, "coerce requirement gave wrong error: `{:?}`", predicate)
658 }
659
660 ty::PredicateKind::Clause(ty::ClauseKind::RegionOutlives(..))
661 | ty::PredicateKind::Clause(ty::ClauseKind::TypeOutlives(..)) => {
662 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("outlives clauses should not error outside borrowck. obligation: `{0:?}`",
obligation))span_bug!(
663 span,
664 "outlives clauses should not error outside borrowck. obligation: `{:?}`",
665 obligation
666 )
667 }
668
669 ty::PredicateKind::Clause(ty::ClauseKind::Projection(..)) => {
670 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("projection clauses should be implied from elsewhere. obligation: `{0:?}`",
obligation))span_bug!(
671 span,
672 "projection clauses should be implied from elsewhere. obligation: `{:?}`",
673 obligation
674 )
675 }
676
677 ty::PredicateKind::DynCompatible(trait_def_id) => {
678 let violations = self.tcx.dyn_compatibility_violations(trait_def_id);
679 let mut err = report_dyn_incompatibility(
680 self.tcx,
681 span,
682 None,
683 trait_def_id,
684 violations,
685 );
686 if let hir::Node::Item(item) =
687 self.tcx.hir_node_by_def_id(obligation.cause.body_def_id)
688 && let hir::ItemKind::Impl(impl_) = item.kind
689 && let None = impl_.of_trait
690 && let hir::TyKind::TraitObject(_, tagged_ptr) = impl_.self_ty.kind
691 && let TraitObjectSyntax::None = tagged_ptr.tag()
692 && impl_.self_ty.span.edition().at_least_rust_2021()
693 {
694 err.downgrade_to_delayed_bug();
697 }
698 err
699 }
700
701 ty::PredicateKind::Clause(ty::ClauseKind::WellFormed(ty)) => {
702 let ty = self.resolve_vars_if_possible(ty);
703 if self.next_trait_solver() {
704 if let Err(guar) = ty.error_reported() {
705 return guar;
706 }
707
708 self.dcx().struct_span_err(
711 span,
712 ::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"),
713 )
714 } else {
715 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("WF predicate not satisfied for {0:?}", ty));span_bug!(span, "WF predicate not satisfied for {:?}", ty);
721 }
722 }
723
724 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(..))
729 | ty::PredicateKind::ConstEquate { .. }
730 | ty::PredicateKind::Ambiguous
731 | ty::PredicateKind::Clause(ty::ClauseKind::UnstableFeature { .. })
732 | ty::PredicateKind::NormalizesTo { .. }
733 | ty::PredicateKind::Clause(ty::ClauseKind::ConstArgHasType { .. }) => {
734 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("Unexpected `Predicate` for `SelectionError`: `{0:?}`",
obligation))span_bug!(
735 span,
736 "Unexpected `Predicate` for `SelectionError`: `{:?}`",
737 obligation
738 )
739 }
740 }
741 }
742
743 SelectionError::SignatureMismatch(SignatureMismatchData {
744 found_trait_ref,
745 expected_trait_ref,
746 terr: terr @ TypeError::CyclicTy(_),
747 }) => self.report_cyclic_signature_error(
748 &obligation,
749 found_trait_ref,
750 expected_trait_ref,
751 terr,
752 ),
753 SelectionError::SignatureMismatch(SignatureMismatchData {
754 found_trait_ref,
755 expected_trait_ref,
756 terr: _,
757 }) => {
758 match self.report_signature_mismatch_error(
759 &obligation,
760 span,
761 found_trait_ref,
762 expected_trait_ref,
763 ) {
764 Ok(err) => err,
765 Err(guar) => return guar,
766 }
767 }
768
769 SelectionError::TraitDynIncompatible(did) => {
770 let violations = self.tcx.dyn_compatibility_violations(did);
771 report_dyn_incompatibility(self.tcx, span, None, did, violations)
772 }
773
774 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsInfer) => {
775 ::rustc_middle::util::bug::bug_fmt(format_args!("MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"))bug!(
776 "MentionsInfer should have been handled in `traits/fulfill.rs` or `traits/select/mod.rs`"
777 )
778 }
779 SelectionError::NotConstEvaluatable(NotConstEvaluatable::MentionsParam) => {
780 match self.report_not_const_evaluatable_error(&obligation, span) {
781 Ok(err) => err,
782 Err(guar) => return guar,
783 }
784 }
785
786 SelectionError::NotConstEvaluatable(NotConstEvaluatable::Error(guar))
788 | SelectionError::Overflow(OverflowError::Error(guar)) => {
789 self.set_tainted_by_errors(guar);
790 return guar;
791 }
792
793 SelectionError::Overflow(_) => {
794 ::rustc_middle::util::bug::bug_fmt(format_args!("overflow should be handled before the `report_selection_error` path"));bug!("overflow should be handled before the `report_selection_error` path");
795 }
796
797 SelectionError::ConstArgHasWrongType { ct, ct_ty, expected_ty } => {
798 let expected_ty_str = self.tcx.short_string(expected_ty, &mut long_ty_file);
799 let ct_str = self.tcx.short_string(ct, &mut long_ty_file);
800 let mut diag = self.dcx().struct_span_err(
801 span,
802 ::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}`"),
803 );
804 diag.long_ty_path = long_ty_file;
805
806 self.note_type_err(
807 &mut diag,
808 &obligation.cause,
809 None,
810 None,
811 TypeError::Sorts(ty::error::ExpectedFound::new(expected_ty, ct_ty)),
812 false,
813 None,
814 );
815 diag
816 }
817 };
818
819 self.note_obligation_cause(&mut err, &obligation);
820 err.emit()
821 }
822}
823
824impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
825 pub(super) fn apply_do_not_recommend(
826 &self,
827 obligation: &mut PredicateObligation<'tcx>,
828 root_obligation: &PredicateObligation<'tcx>,
829 ) -> bool {
830 let mut base_cause = obligation.cause.code().clone();
831 let mut applied_do_not_recommend = false;
832 loop {
833 if let ObligationCauseCode::ImplDerived(ref c) = base_cause {
834 if self.tcx.do_not_recommend_impl(c.impl_or_alias_def_id) {
835 let code = (*c.derived.parent_code).clone();
836 if code == *root_obligation.cause.code()
839 && root_obligation.cause.span.eq_ctxt(obligation.cause.span)
840 && !root_obligation.cause.span.contains(obligation.cause.span)
841 {
842 obligation.cause.span = root_obligation.cause.span;
843 }
844 obligation.cause.map_code(|_| code);
845 obligation.predicate = c.derived.parent_trait_pred.upcast(self.tcx);
846 applied_do_not_recommend = true;
847 }
848 }
849 if let Some(parent_cause) = base_cause.parent() {
850 base_cause = parent_cause.clone();
851 } else {
852 break;
853 }
854 }
855
856 applied_do_not_recommend
857 }
858
859 fn report_host_effect_error(
860 &self,
861 clause: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>,
862 main_obligation: &PredicateObligation<'tcx>,
863 span: Span,
864 ) -> Diag<'a> {
865 let trait_ref = clause.map_bound(|clause| ty::TraitPredicate {
869 trait_ref: clause.trait_ref,
870 polarity: ty::PredicatePolarity::Positive,
871 });
872 let mut file = None;
873
874 let err_msg = self.get_standard_error_message(
875 trait_ref,
876 Some(clause.constness()),
877 String::new(),
878 &mut file,
879 );
880 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);
881 *diag.long_ty_path() = file;
882 let obligation = Obligation::new(
883 self.tcx,
884 ObligationCause::dummy(),
885 main_obligation.param_env,
886 trait_ref,
887 );
888 if !self.predicate_may_hold(&obligation) {
889 diag.downgrade_to_delayed_bug();
890 }
891
892 if let Ok(Some(ImplSource::UserDefined(impl_data))) =
893 self.enter_forall(trait_ref, |trait_ref_for_select| {
894 SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref_for_select))
895 })
896 {
897 let impl_did = impl_data.impl_def_id;
898 let trait_did = trait_ref.def_id();
899 let impl_span = self.tcx.def_span(impl_did);
900 let trait_name = self.tcx.item_name(trait_did);
901
902 if self.tcx.is_const_trait(trait_did) && !self.tcx.is_const_trait_impl(impl_did) {
903 if !impl_did.is_local() {
904 diag.span_note(
905 impl_span,
906 ::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`"),
907 );
908 }
909
910 if let Some(command) =
911 {
{
'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::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.tcx, impl_did, OnConst {directive, ..} => directive.as_deref())
912 .flatten()
913 {
914 let (_, mut format_args) = self.on_unimplemented_components(
915 trait_ref,
916 main_obligation,
917 diag.long_ty_path(),
918 false,
919 );
920 if let ty::Adt(def, args) = trait_ref.self_ty().skip_binder().kind() {
921 for param in self.tcx.generics_of(def.did()).own_params.iter() {
922 match param.kind {
923 GenericParamDefKind::Type { .. }
924 | GenericParamDefKind::Const { .. } => {
925 format_args
926 .generic_args
927 .push((param.name, args[param.index as usize].to_string()));
928 }
929 _ => continue,
930 }
931 }
932 }
933 let CustomDiagnostic { message, label, notes, parent_label: _ } =
934 command.eval(None, &format_args);
935
936 if let Some(message) = message {
937 diag.primary_message(message);
938 }
939 if let Some(label) = label {
940 diag.span_label(span, label);
941 }
942 for note in notes {
943 diag.note(note);
944 }
945 } else if let Some(impl_did) = impl_did.as_local()
946 && let item = self.tcx.hir_expect_item(impl_did)
947 && let hir::ItemKind::Impl(impl_) = item.kind
948 && impl_.of_trait.is_some()
949 {
950 diag.span_suggestion_verbose(
952 item.span.shrink_to_lo(),
953 ::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`"),
954 "const ".to_string(),
955 Applicability::MaybeIncorrect,
956 );
957 }
958 }
959 } else if let ty::Param(param) = trait_ref.self_ty().skip_binder().kind()
960 && let Some(generics) =
961 self.tcx.hir_node_by_def_id(main_obligation.cause.body_def_id).generics()
962 {
963 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!(
964 "[const] {}",
965 trait_ref.map_bound(|tr| tr.trait_ref).print_trait_sugared(),
966 ));
967 ty::suggest_constraining_type_param(
968 self.tcx,
969 generics,
970 &mut diag,
971 param.name.as_str(),
972 &constraint,
973 Some(trait_ref.def_id()),
974 None,
975 );
976 }
977 diag
978 }
979
980 fn emit_specialized_closure_kind_error(
981 &self,
982 obligation: &PredicateObligation<'tcx>,
983 mut trait_pred: ty::PolyTraitPredicate<'tcx>,
984 ) -> Option<ErrorGuaranteed> {
985 if self.tcx.is_lang_item(trait_pred.def_id(), LangItem::AsyncFnKindHelper) {
988 let mut code = obligation.cause.code();
989 if let ObligationCauseCode::FunctionArg { parent_code, .. } = code {
991 code = &**parent_code;
992 }
993 if let Some((_, Some(parent))) = code.parent_with_predicate() {
995 trait_pred = parent;
996 }
997 }
998
999 let self_ty = trait_pred.self_ty().skip_binder();
1000
1001 let (expected_kind, trait_prefix) =
1002 if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) {
1003 (expected_kind, "")
1004 } else if let Some(expected_kind) =
1005 self.tcx.async_fn_trait_kind_from_def_id(trait_pred.def_id())
1006 {
1007 (expected_kind, "Async")
1008 } else {
1009 return None;
1010 };
1011
1012 let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() {
1013 ty::Closure(def_id, args) => {
1014 (def_id, args.as_closure().sig().map_bound(|sig| sig.inputs()[0]), false)
1015 }
1016 ty::CoroutineClosure(def_id, args) => (
1017 def_id,
1018 args.as_coroutine_closure()
1019 .coroutine_closure_sig()
1020 .map_bound(|sig| sig.tupled_inputs_ty),
1021 !args.as_coroutine_closure().tupled_upvars_ty().is_ty_var()
1022 && args.as_coroutine_closure().has_self_borrows(),
1023 ),
1024 _ => return None,
1025 };
1026
1027 let expected_args = trait_pred.map_bound(|trait_pred| trait_pred.trait_ref.args.type_at(1));
1028
1029 if self.enter_forall(found_args, |found_args| {
1032 self.enter_forall(expected_args, |expected_args| {
1033 !self.can_eq(obligation.param_env, expected_args, found_args)
1034 })
1035 }) {
1036 return None;
1037 }
1038
1039 if let Some(found_kind) = self.closure_kind(self_ty)
1040 && !found_kind.extends(expected_kind)
1041 {
1042 let mut err = self.report_closure_error(
1043 &obligation,
1044 closure_def_id,
1045 found_kind,
1046 expected_kind,
1047 trait_prefix,
1048 );
1049 self.note_obligation_cause(&mut err, &obligation);
1050 return Some(err.emit());
1051 }
1052
1053 if has_self_borrows && expected_kind != ty::ClosureKind::FnOnce {
1057 let coro_kind = match self
1058 .tcx
1059 .coroutine_kind(self.tcx.coroutine_for_closure(closure_def_id))
1060 .unwrap()
1061 {
1062 rustc_hir::CoroutineKind::Desugared(desugaring, _) => desugaring.to_string(),
1063 coro => coro.to_string(),
1064 };
1065 let mut err = self.dcx().create_err(CoroClosureNotFn {
1066 span: self.tcx.def_span(closure_def_id),
1067 kind: expected_kind.as_str(),
1068 coro_kind,
1069 });
1070 self.note_obligation_cause(&mut err, &obligation);
1071 return Some(err.emit());
1072 }
1073
1074 None
1075 }
1076
1077 fn fn_arg_obligation(
1078 &self,
1079 obligation: &PredicateObligation<'tcx>,
1080 ) -> Result<(), ErrorGuaranteed> {
1081 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1082 && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
1083 && let arg = arg.peel_borrows()
1084 && let hir::ExprKind::Path(hir::QPath::Resolved(
1085 None,
1086 hir::Path { res: hir::def::Res::Local(hir_id), .. },
1087 )) = arg.kind
1088 && let Node::Pat(pat) = self.tcx.hir_node(*hir_id)
1089 && let Some((preds, guar)) = self.reported_trait_errors.borrow().get(&pat.span)
1090 && preds.contains(&obligation.as_goal())
1091 {
1092 return Err(*guar);
1093 }
1094 Ok(())
1095 }
1096
1097 fn detect_negative_literal(
1098 &self,
1099 obligation: &PredicateObligation<'tcx>,
1100 trait_pred: ty::PolyTraitPredicate<'tcx>,
1101 err: &mut Diag<'_>,
1102 ) -> bool {
1103 if let ObligationCauseCode::UnOp { hir_id, .. } = obligation.cause.code()
1104 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1105 && let hir::ExprKind::Unary(hir::UnOp::Neg, inner) = expr.kind
1106 && let hir::ExprKind::Lit(lit) = inner.kind
1107 && let LitKind::Int(_, LitIntType::Unsuffixed) = lit.node
1108 {
1109 err.span_suggestion_verbose(
1110 lit.span.shrink_to_hi(),
1111 "consider specifying an integer type that can be negative",
1112 match trait_pred.skip_binder().self_ty().kind() {
1113 ty::Uint(ty::UintTy::Usize) => "isize",
1114 ty::Uint(ty::UintTy::U8) => "i8",
1115 ty::Uint(ty::UintTy::U16) => "i16",
1116 ty::Uint(ty::UintTy::U32) => "i32",
1117 ty::Uint(ty::UintTy::U64) => "i64",
1118 ty::Uint(ty::UintTy::U128) => "i128",
1119 _ => "i64",
1120 }
1121 .to_string(),
1122 Applicability::MaybeIncorrect,
1123 );
1124 return true;
1125 }
1126 false
1127 }
1128
1129 fn try_conversion_context(
1133 &self,
1134 obligation: &PredicateObligation<'tcx>,
1135 trait_pred: ty::PolyTraitPredicate<'tcx>,
1136 err: &mut Diag<'_>,
1137 ) -> (bool, bool) {
1138 let span = obligation.cause.span;
1139 struct FindMethodSubexprOfTry {
1141 search_span: Span,
1142 }
1143 impl<'v> Visitor<'v> for FindMethodSubexprOfTry {
1144 type Result = ControlFlow<&'v hir::Expr<'v>>;
1145 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
1146 if let hir::ExprKind::Match(expr, _arms, hir::MatchSource::TryDesugar(_)) = ex.kind
1147 && ex.span.with_lo(ex.span.hi() - BytePos(1)).source_equal(self.search_span)
1148 && let hir::ExprKind::Call(_, [expr, ..]) = expr.kind
1149 {
1150 ControlFlow::Break(expr)
1151 } else {
1152 hir::intravisit::walk_expr(self, ex)
1153 }
1154 }
1155 }
1156 let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_def_id);
1157 let Some(body_id) = self.tcx.hir_node(hir_id).body_id() else { return (false, false) };
1158 let ControlFlow::Break(expr) =
1159 (FindMethodSubexprOfTry { search_span: span }).visit_body(self.tcx.hir_body(body_id))
1160 else {
1161 return (false, false);
1162 };
1163 let Some(typeck) = &self.typeck_results else {
1164 return (false, false);
1165 };
1166 let ObligationCauseCode::QuestionMark = obligation.cause.code().peel_derives() else {
1167 return (false, false);
1168 };
1169 let self_ty = trait_pred.skip_binder().self_ty();
1170 let found_ty = trait_pred.skip_binder().trait_ref.args.get(1).and_then(|a| a.as_type());
1171 let noted_missing_impl =
1172 self.note_missing_impl_for_question_mark(err, self_ty, found_ty, trait_pred);
1173
1174 let mut prev_ty = self.resolve_vars_if_possible(
1175 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1176 );
1177
1178 let get_e_type = |prev_ty: Ty<'tcx>| -> Option<Ty<'tcx>> {
1182 let ty::Adt(def, args) = prev_ty.kind() else {
1183 return None;
1184 };
1185 let Some(arg) = args.get(1) else {
1186 return None;
1187 };
1188 if !self.tcx.is_diagnostic_item(sym::Result, def.did()) {
1189 return None;
1190 }
1191 arg.as_type()
1192 };
1193
1194 let mut suggested = false;
1195 let mut chain = ::alloc::vec::Vec::new()vec![];
1196
1197 let mut expr = expr;
1199 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
1200 expr = rcvr_expr;
1204 chain.push((span, prev_ty));
1205
1206 let next_ty = self.resolve_vars_if_possible(
1207 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1208 );
1209
1210 let is_diagnostic_item = |symbol: Symbol, ty: Ty<'tcx>| {
1211 let ty::Adt(def, _) = ty.kind() else {
1212 return false;
1213 };
1214 self.tcx.is_diagnostic_item(symbol, def.did())
1215 };
1216 if let Some(ty) = get_e_type(prev_ty)
1220 && let Some(found_ty) = found_ty
1221 && (
1226 ( path_segment.ident.name == sym::map_err
1228 && is_diagnostic_item(sym::Result, next_ty)
1229 ) || ( path_segment.ident.name == sym::ok_or_else
1231 && is_diagnostic_item(sym::Option, next_ty)
1232 )
1233 )
1234 && let ty::Tuple(tys) = found_ty.kind()
1236 && tys.is_empty()
1237 && self.can_eq(obligation.param_env, ty, found_ty)
1239 && let [arg] = args
1241 && let hir::ExprKind::Closure(closure) = arg.kind
1242 && let body = self.tcx.hir_body(closure.body)
1244 && let hir::ExprKind::Block(block, _) = body.value.kind
1245 && let None = block.expr
1246 && let [.., stmt] = block.stmts
1248 && let hir::StmtKind::Semi(expr) = stmt.kind
1249 && let expr_ty = self.resolve_vars_if_possible(
1250 typeck.expr_ty_adjusted_opt(expr)
1251 .unwrap_or(Ty::new_misc_error(self.tcx)),
1252 )
1253 && self
1254 .infcx
1255 .type_implements_trait(
1256 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1257 [self_ty, expr_ty],
1258 obligation.param_env,
1259 )
1260 .must_apply_modulo_regions()
1261 {
1262 suggested = true;
1263 err.span_suggestion_short(
1264 stmt.span.with_lo(expr.span.hi()),
1265 "remove this semicolon",
1266 String::new(),
1267 Applicability::MachineApplicable,
1268 );
1269 }
1270
1271 prev_ty = next_ty;
1272
1273 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1274 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
1275 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
1276 {
1277 let parent = self.tcx.parent_hir_node(binding.hir_id);
1278 if let hir::Node::LetStmt(local) = parent
1280 && let Some(binding_expr) = local.init
1281 {
1282 expr = binding_expr;
1284 }
1285 if let hir::Node::Param(_param) = parent {
1286 break;
1288 }
1289 }
1290 }
1291 prev_ty = self.resolve_vars_if_possible(
1295 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1296 );
1297 chain.push((expr.span, prev_ty));
1298
1299 let mut prev = None;
1300 let mut iter = chain.into_iter().rev().peekable();
1301 while let Some((span, err_ty)) = iter.next() {
1302 let is_last = iter.peek().is_none();
1303 let err_ty = get_e_type(err_ty);
1304 let err_ty = match (err_ty, prev) {
1305 (Some(err_ty), Some(prev)) if !self.can_eq(obligation.param_env, err_ty, prev) => {
1306 err_ty
1307 }
1308 (Some(err_ty), None) => err_ty,
1309 _ => {
1310 prev = err_ty;
1311 continue;
1312 }
1313 };
1314
1315 let implements_from = self
1316 .infcx
1317 .type_implements_trait(
1318 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1319 [self_ty, err_ty],
1320 obligation.param_env,
1321 )
1322 .must_apply_modulo_regions();
1323
1324 let err_ty_str = self.tcx.short_string(err_ty, err.long_ty_path());
1325 let label = if !implements_from && is_last {
1326 ::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!(
1327 "this can't be annotated with `?` because it has type `Result<_, {err_ty_str}>`"
1328 )
1329 } else {
1330 ::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}>`")
1331 };
1332
1333 if !suggested || !implements_from {
1334 err.span_label(span, label);
1335 }
1336 prev = Some(err_ty);
1337 }
1338 (suggested, noted_missing_impl)
1339 }
1340
1341 fn note_missing_impl_for_question_mark(
1342 &self,
1343 err: &mut Diag<'_>,
1344 self_ty: Ty<'_>,
1345 found_ty: Option<Ty<'_>>,
1346 trait_pred: ty::PolyTraitPredicate<'tcx>,
1347 ) -> bool {
1348 match (self_ty.kind(), found_ty) {
1349 (ty::Adt(def, _), Some(ty))
1350 if let ty::Adt(found, _) = ty.kind()
1351 && def.did().is_local()
1352 && found.did().is_local() =>
1353 {
1354 err.span_note(
1355 self.tcx.def_span(def.did()),
1356 ::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}>`"),
1357 );
1358 }
1359 (ty::Adt(def, _), None) if def.did().is_local() => {
1360 let trait_path = self.tcx.short_string(
1361 trait_pred.skip_binder().trait_ref.print_only_trait_path(),
1362 err.long_ty_path(),
1363 );
1364 err.span_note(
1365 self.tcx.def_span(def.did()),
1366 ::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}`"),
1367 );
1368 }
1369 (ty::Adt(def, _), Some(ty)) if def.did().is_local() => {
1370 err.span_note(
1371 self.tcx.def_span(def.did()),
1372 ::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}>`"),
1373 );
1374 }
1375 (_, Some(ty))
1376 if let ty::Adt(def, _) = ty.kind()
1377 && def.did().is_local() =>
1378 {
1379 err.span_note(
1380 self.tcx.def_span(def.did()),
1381 ::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}>`"),
1382 );
1383 }
1384 _ => return false,
1385 }
1386 true
1387 }
1388
1389 fn report_const_param_not_wf(
1390 &self,
1391 ty: Ty<'tcx>,
1392 obligation: &PredicateObligation<'tcx>,
1393 ) -> Diag<'a> {
1394 let def_id = obligation.cause.body_def_id;
1395 let span = self.tcx.ty_span(def_id);
1396
1397 let mut file = None;
1398 let ty_str = self.tcx.short_string(ty, &mut file);
1399 let mut diag = match ty.kind() {
1400 ty::Float(_) => {
1401 {
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!(
1402 self.dcx(),
1403 span,
1404 E0741,
1405 "`{ty_str}` is forbidden as the type of a const generic parameter",
1406 )
1407 }
1408 ty::FnPtr(..) => {
1409 {
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!(
1410 self.dcx(),
1411 span,
1412 E0741,
1413 "using function pointers as const generic parameters is forbidden",
1414 )
1415 }
1416 ty::RawPtr(_, _) => {
1417 {
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!(
1418 self.dcx(),
1419 span,
1420 E0741,
1421 "using raw pointers as const generic parameters is forbidden",
1422 )
1423 }
1424 ty::Adt(def, _) => {
1425 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!(
1427 self.dcx(),
1428 span,
1429 E0741,
1430 "`{ty_str}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
1431 );
1432 if let Some(span) = self.tcx.hir_span_if_local(def.did())
1435 && obligation.cause.code().parent().is_none()
1436 {
1437 if ty.is_structural_eq_shallow(self.tcx) {
1438 diag.span_suggestion(
1439 span.shrink_to_lo(),
1440 ::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()),
1441 "#[derive(ConstParamTy)]\n",
1442 Applicability::MachineApplicable,
1443 );
1444 } else {
1445 diag.span_suggestion(
1448 span.shrink_to_lo(),
1449 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {0}",
def.descr()))
})format!(
1450 "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {}",
1451 def.descr()
1452 ),
1453 "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1454 Applicability::MachineApplicable,
1455 );
1456 }
1457 }
1458 diag
1459 }
1460 _ => {
1461 {
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!(
1462 self.dcx(),
1463 span,
1464 E0741,
1465 "`{ty_str}` can't be used as a const parameter type",
1466 )
1467 }
1468 };
1469 diag.long_ty_path = file;
1470
1471 let mut code = obligation.cause.code();
1472 let mut pred = obligation.predicate.as_trait_clause();
1473 while let Some((next_code, next_pred)) = code.parent_with_predicate() {
1474 if let Some(pred) = pred {
1475 self.enter_forall(pred, |pred| {
1476 let ty = self.tcx.short_string(pred.self_ty(), diag.long_ty_path());
1477 let trait_path = self
1478 .tcx
1479 .short_string(pred.print_modifiers_and_trait_path(), diag.long_ty_path());
1480 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"));
1481 })
1482 }
1483 code = next_code;
1484 pred = next_pred;
1485 }
1486
1487 diag
1488 }
1489}
1490
1491impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
1492 fn can_match_trait(
1493 &self,
1494 param_env: ty::ParamEnv<'tcx>,
1495 goal: ty::TraitPredicate<'tcx>,
1496 assumption: ty::PolyTraitPredicate<'tcx>,
1497 ) -> bool {
1498 if goal.polarity != assumption.polarity() {
1500 return false;
1501 }
1502
1503 let trait_assumption = self.instantiate_binder_with_fresh_vars(
1504 DUMMY_SP,
1505 infer::BoundRegionConversionTime::HigherRankedType,
1506 assumption,
1507 );
1508
1509 self.can_eq(param_env, goal.trait_ref, trait_assumption.trait_ref)
1510 }
1511
1512 fn can_match_host_effect(
1513 &self,
1514 param_env: ty::ParamEnv<'tcx>,
1515 goal: ty::HostEffectClause<'tcx>,
1516 assumption: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>,
1517 ) -> bool {
1518 let assumption = self.instantiate_binder_with_fresh_vars(
1519 DUMMY_SP,
1520 infer::BoundRegionConversionTime::HigherRankedType,
1521 assumption,
1522 );
1523
1524 assumption.constness.satisfies(goal.constness)
1525 && self.can_eq(param_env, goal.trait_ref, assumption.trait_ref)
1526 }
1527
1528 fn as_host_effect_clause(
1529 predicate: ty::Predicate<'tcx>,
1530 ) -> Option<ty::Binder<'tcx, ty::HostEffectClause<'tcx>>> {
1531 predicate.as_clause().and_then(|clause| match clause.kind().skip_binder() {
1532 ty::ClauseKind::HostEffect(host_clause) => Some(clause.kind().rebind(host_clause)),
1533 _ => None,
1534 })
1535 }
1536
1537 fn can_match_projection(
1538 &self,
1539 param_env: ty::ParamEnv<'tcx>,
1540 goal: ty::ProjectionPredicate<'tcx>,
1541 assumption: ty::PolyProjectionPredicate<'tcx>,
1542 ) -> bool {
1543 let assumption = self.instantiate_binder_with_fresh_vars(
1544 DUMMY_SP,
1545 infer::BoundRegionConversionTime::HigherRankedType,
1546 assumption,
1547 );
1548
1549 self.can_eq(param_env, goal.projection_term, assumption.projection_term)
1550 && self.can_eq(param_env, goal.term, assumption.term)
1551 }
1552
1553 x;#[instrument(level = "debug", skip(self), ret)]
1556 pub(super) fn error_implies(
1557 &self,
1558 cond: Goal<'tcx, ty::Predicate<'tcx>>,
1559 error: Goal<'tcx, ty::Predicate<'tcx>>,
1560 ) -> bool {
1561 if cond == error {
1562 return true;
1563 }
1564
1565 if cond.param_env != error.param_env {
1569 return false;
1570 }
1571 let param_env = error.param_env;
1572
1573 if let Some(error) = error.predicate.as_trait_clause() {
1574 self.enter_forall(error, |error| {
1575 elaborate(self.tcx, std::iter::once(cond.predicate))
1576 .filter_map(|implied| implied.as_trait_clause())
1577 .any(|implied| self.can_match_trait(param_env, error, implied))
1578 })
1579 } else if let Some(error) = Self::as_host_effect_clause(error.predicate) {
1580 self.enter_forall(error, |error| {
1581 elaborate(self.tcx, std::iter::once(cond.predicate))
1582 .filter_map(Self::as_host_effect_clause)
1583 .any(|implied| self.can_match_host_effect(param_env, error, implied))
1584 })
1585 } else if let Some(error) = error.predicate.as_projection_clause() {
1586 self.enter_forall(error, |error| {
1587 elaborate(self.tcx, std::iter::once(cond.predicate))
1588 .filter_map(|implied| implied.as_projection_clause())
1589 .any(|implied| self.can_match_projection(param_env, error, implied))
1590 })
1591 } else {
1592 false
1593 }
1594 }
1595
1596 #[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("compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
::tracing_core::__macro_support::Option::Some(1596u32),
::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.resolve_vars_if_possible(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.resolve_vars_if_possible(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.resolve_vars_if_possible(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,
{
let _guard = ForceTrimmedGuard::new();
Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("type mismatch resolving `{0}`",
self.tcx.short_string(self.resolve_vars_if_possible(predicate),
diag.long_ty_path())))
}))
}, true)),
_ => None,
}
});
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()
})
}
}
}#[instrument(level = "debug", skip_all)]
1597 pub(super) fn report_projection_error(
1598 &self,
1599 obligation: &PredicateObligation<'tcx>,
1600 error: &MismatchedProjectionTypes<'tcx>,
1601 ) -> ErrorGuaranteed {
1602 let predicate = self.resolve_vars_if_possible(obligation.predicate);
1603
1604 if let Err(e) = predicate.error_reported() {
1605 return e;
1606 }
1607
1608 self.probe(|_| {
1609 let bound_predicate = predicate.kind();
1614 let (values, err) = match bound_predicate.skip_binder() {
1615 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
1616 let ocx = ObligationCtxt::new(self);
1617
1618 let data = self.instantiate_binder_with_fresh_vars(
1619 obligation.cause.span,
1620 infer::BoundRegionConversionTime::HigherRankedType,
1621 bound_predicate.rebind(data),
1622 );
1623 let unnormalized_term = data.projection_term.to_term(self.tcx, ty::IsRigid::No);
1624 let normalized_term = ocx.normalize(
1627 &obligation.cause,
1628 obligation.param_env,
1629 Unnormalized::new_wip(unnormalized_term),
1630 );
1631
1632 let _ = ocx.try_evaluate_obligations();
1638
1639 if let Err(new_err) =
1640 ocx.eq(&obligation.cause, obligation.param_env, data.term, normalized_term)
1641 {
1642 (
1643 Some((
1644 data.projection_term,
1645 self.resolve_vars_if_possible(normalized_term),
1646 data.term,
1647 )),
1648 new_err,
1649 )
1650 } else {
1651 (None, error.err)
1652 }
1653 }
1654 _ => (None, error.err),
1655 };
1656
1657 let mut file = None;
1658 let (msg, mut span, mut closure_span) = values
1659 .and_then(|(predicate, normalized_term, expected_term)| {
1660 self.maybe_detailed_projection_msg(
1661 obligation.cause.span,
1662 predicate,
1663 normalized_term,
1664 expected_term,
1665 &mut file,
1666 )
1667 })
1668 .unwrap_or_else(|| {
1669 (
1670 with_forced_trimmed_paths!(format!(
1671 "type mismatch resolving `{}`",
1672 self.tcx
1673 .short_string(self.resolve_vars_if_possible(predicate), &mut file),
1674 )),
1675 obligation.cause.span,
1676 None,
1677 )
1678 });
1679
1680 if closure_span.is_none()
1684 && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1685 && let Node::Expr(arg_expr) = self.tcx.hir_node(*arg_hir_id)
1686 && let hir::ExprKind::Closure(closure) = arg_expr.kind
1687 && closure.kind == hir::ClosureKind::Closure
1688 {
1689 let body = self.tcx.hir_body(closure.body);
1690 let ret_span = match body.value.kind {
1691 hir::ExprKind::Block(hir::Block { expr: Some(expr), .. }, _) => expr.span,
1692 hir::ExprKind::Block(hir::Block { expr: None, stmts: [.., last], .. }, _) => {
1693 last.span
1694 }
1695 _ => body.value.span,
1696 };
1697 if !closure.fn_decl_span.overlaps(ret_span) {
1698 closure_span = Some(closure.fn_decl_span);
1699 span = ret_span;
1700 }
1701 }
1702
1703 let mut diag = struct_span_code_err!(self.dcx(), span, E0271, "{msg}");
1704 *diag.long_ty_path() = file;
1705 let mut mention_bounds = true;
1706 if let Some(span) = closure_span {
1707 if let Some((_, _, expected_ty)) = values
1708 && let Some(expected_ty) = expected_ty.as_type()
1709 && let ty::Closure(def_id, _) = expected_ty.kind()
1710 && self.tcx.def_span(*def_id).overlaps(span)
1711 && let ObligationCauseCode::FunctionArg { parent_code, arg_hir_id, .. } =
1712 obligation.cause.code()
1713 && let ObligationCauseCode::WhereClauseInExpr(def_id, span, _, _)
1714 | ObligationCauseCode::WhereClause(def_id, span) = &**parent_code
1715 {
1716 let mut multispan: MultiSpan = (*span).into();
1721 multispan.push_span_label(*span, "this requires the closure to return itself");
1722 if let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) {
1723 multispan
1724 .push_span_label(arg.span, "this closure would have to return itself");
1725 }
1726 let in_the_item = match self.tcx.opt_item_name(*def_id) {
1727 Some(name) => format!("in `{name}`"),
1728 None => String::new(),
1729 };
1730 diag.span_note(
1731 multispan,
1732 format!(
1733 "a bound {in_the_item} requires that a closure return itself, which is \
1734 not possible",
1735 ),
1736 );
1737 mention_bounds = false;
1738 } else {
1739 diag.span_label(span, "this closure");
1756 if !span.overlaps(obligation.cause.span) {
1757 diag.span_label(obligation.cause.span, "closure used here");
1759 }
1760 }
1761 }
1762
1763 let secondary_span = self.probe(|_| {
1764 let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1765 predicate.kind().skip_binder()
1766 else {
1767 return None;
1768 };
1769 if !proj.projection_term.kind.is_trait_projection() {
1770 return None;
1771 }
1772
1773 let trait_ref = self.enter_forall_and_leak_universe(
1774 predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)),
1775 );
1776 let Ok(Some(ImplSource::UserDefined(impl_data))) =
1777 SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref))
1778 else {
1779 return None;
1780 };
1781
1782 let Ok(node) =
1783 specialization_graph::assoc_def(self.tcx, impl_data.impl_def_id, proj.def_id())
1784 else {
1785 return None;
1786 };
1787
1788 if !node.is_final() {
1789 return None;
1790 }
1791
1792 match self.tcx.hir_get_if_local(node.item.def_id) {
1793 Some(
1794 hir::Node::TraitItem(hir::TraitItem {
1795 kind: hir::TraitItemKind::Type(_, Some(ty)),
1796 ..
1797 })
1798 | hir::Node::ImplItem(hir::ImplItem {
1799 kind: hir::ImplItemKind::Type(ty),
1800 ..
1801 }),
1802 ) => Some((
1803 ty.span,
1804 with_forced_trimmed_paths!(Cow::from(format!(
1805 "type mismatch resolving `{}`",
1806 self.tcx.short_string(
1807 self.resolve_vars_if_possible(predicate),
1808 diag.long_ty_path()
1809 ),
1810 ))),
1811 true,
1812 )),
1813 _ => None,
1814 }
1815 });
1816
1817 self.note_type_err(
1818 &mut diag,
1819 &obligation.cause,
1820 secondary_span,
1821 values.map(|(_, normalized_ty, expected_ty)| {
1822 obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(
1823 expected_ty,
1824 normalized_ty,
1825 )))
1826 }),
1827 err,
1828 false,
1829 Some(span),
1830 );
1831 if mention_bounds {
1832 self.note_obligation_cause(&mut diag, obligation);
1833 }
1834 diag.emit()
1835 })
1836 }
1837
1838 fn maybe_detailed_projection_msg(
1839 &self,
1840 mut span: Span,
1841 projection_term: ty::AliasTerm<'tcx>,
1842 normalized_ty: ty::Term<'tcx>,
1843 expected_ty: ty::Term<'tcx>,
1844 long_ty_path: &mut Option<PathBuf>,
1845 ) -> Option<(String, Span, Option<Span>)> {
1846 if !projection_term.kind.is_trait_projection() {
1847 return None;
1848 }
1849
1850 let projection_def_id = projection_term.expect_projection_def_id();
1851 let trait_def_id = projection_term.trait_def_id(self.tcx);
1852 let self_ty = projection_term.self_ty();
1853
1854 {
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! {
1855 if self.tcx.is_lang_item(projection_def_id, LangItem::FnOnceOutput) {
1856 let (span, closure_span) = if let ty::Closure(def_id, _) = *self_ty.kind() {
1857 let def_span = self.tcx.def_span(def_id);
1858 if let Some(local_def_id) = def_id.as_local()
1859 && let node = self.tcx.hir_node_by_def_id(local_def_id)
1860 && let Some(fn_decl) = node.fn_decl()
1861 && let Some(id) = node.body_id()
1862 {
1863 span = match fn_decl.output {
1864 hir::FnRetTy::Return(ty) => ty.span,
1865 hir::FnRetTy::DefaultReturn(_) => {
1866 let body = self.tcx.hir_body(id);
1867 match body.value.kind {
1868 hir::ExprKind::Block(
1869 hir::Block { expr: Some(expr), .. },
1870 _,
1871 ) => expr.span,
1872 hir::ExprKind::Block(
1873 hir::Block {
1874 expr: None, stmts: [.., last], ..
1875 },
1876 _,
1877 ) => last.span,
1878 _ => body.value.span,
1879 }
1880 }
1881 };
1882 }
1883 (span, Some(def_span))
1884 } else {
1885 (span, None)
1886 };
1887 let item = match self_ty.kind() {
1888 ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
1889 _ => self.tcx.short_string(self_ty, long_ty_path),
1890 };
1891 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1892 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1893 Some((format!(
1894 "expected `{item}` to return `{expected_ty}`, but it returns `{normalized_ty}`",
1895 ), span, closure_span))
1896 } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
1897 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1898 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1899 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1900 Some((format!(
1901 "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
1902 resolves to `{normalized_ty}`"
1903 ), span, None))
1904 } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
1905 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1906 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1907 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1908 Some((format!(
1909 "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
1910 yields `{normalized_ty}`"
1911 ), span, None))
1912 } else {
1913 None
1914 }
1915 }
1916 }
1917
1918 pub fn fuzzy_match_tys(
1919 &self,
1920 mut a: Ty<'tcx>,
1921 mut b: Ty<'tcx>,
1922 ignoring_lifetimes: bool,
1923 ) -> Option<CandidateSimilarity> {
1924 fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
1927 match t.kind() {
1928 ty::Bool => Some(0),
1929 ty::Char => Some(1),
1930 ty::Str => Some(2),
1931 ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => Some(2),
1932 ty::Int(..)
1933 | ty::Uint(..)
1934 | ty::Float(..)
1935 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
1936 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1937 ty::Array(..) | ty::Slice(..) => Some(6),
1938 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1939 ty::Dynamic(..) => Some(8),
1940 ty::Closure(..) => Some(9),
1941 ty::Tuple(..) => Some(10),
1942 ty::Param(..) => Some(11),
1943 ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. }, .. }) => Some(12),
1944 ty::Alias(_, ty::AliasTy { kind: ty::Inherent { .. }, .. }) => Some(13),
1945 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => Some(14),
1946 ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) => Some(15),
1947 ty::Never => Some(16),
1948 ty::Adt(..) => Some(17),
1949 ty::Coroutine(..) => Some(18),
1950 ty::Foreign(..) => Some(19),
1951 ty::CoroutineWitness(..) => Some(20),
1952 ty::CoroutineClosure(..) => Some(21),
1953 ty::Pat(..) => Some(22),
1954 ty::UnsafeBinder(..) => Some(23),
1955 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1956 }
1957 }
1958
1959 let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
1960 loop {
1961 match t.kind() {
1962 ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => t = *inner,
1963 _ => break t,
1964 }
1965 }
1966 };
1967
1968 if !ignoring_lifetimes {
1969 a = strip_references(a);
1970 b = strip_references(b);
1971 }
1972
1973 let cat_a = type_category(self.tcx, a)?;
1974 let cat_b = type_category(self.tcx, b)?;
1975 if a == b {
1976 Some(CandidateSimilarity::Exact { ignoring_lifetimes })
1977 } else if cat_a == cat_b {
1978 match (a.kind(), b.kind()) {
1979 (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
1980 (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
1981 (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
1987 self.fuzzy_match_tys(a, b, true).is_some()
1988 }
1989 _ => true,
1990 }
1991 .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
1992 } else if ignoring_lifetimes {
1993 None
1994 } else {
1995 self.fuzzy_match_tys(a, b, true)
1996 }
1997 }
1998
1999 pub(super) fn describe_closure(&self, kind: hir::ClosureKind) -> &'static str {
2000 match kind {
2001 hir::ClosureKind::Closure => "a closure",
2002 hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => "a coroutine",
2003 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2004 hir::CoroutineDesugaring::Async,
2005 hir::CoroutineSource::Block,
2006 )) => "an async block",
2007 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2008 hir::CoroutineDesugaring::Async,
2009 hir::CoroutineSource::Fn,
2010 )) => "an async function",
2011 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2012 hir::CoroutineDesugaring::Async,
2013 hir::CoroutineSource::Closure,
2014 ))
2015 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
2016 "an async closure"
2017 }
2018 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2019 hir::CoroutineDesugaring::AsyncGen,
2020 hir::CoroutineSource::Block,
2021 )) => "an async gen block",
2022 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2023 hir::CoroutineDesugaring::AsyncGen,
2024 hir::CoroutineSource::Fn,
2025 )) => "an async gen function",
2026 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2027 hir::CoroutineDesugaring::AsyncGen,
2028 hir::CoroutineSource::Closure,
2029 ))
2030 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
2031 "an async gen closure"
2032 }
2033 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2034 hir::CoroutineDesugaring::Gen,
2035 hir::CoroutineSource::Block,
2036 )) => "a gen block",
2037 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2038 hir::CoroutineDesugaring::Gen,
2039 hir::CoroutineSource::Fn,
2040 )) => "a gen function",
2041 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2042 hir::CoroutineDesugaring::Gen,
2043 hir::CoroutineSource::Closure,
2044 ))
2045 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => "a gen closure",
2046 }
2047 }
2048
2049 pub(super) fn find_similar_impl_candidates(
2050 &self,
2051 trait_pred: ty::PolyTraitPredicate<'tcx>,
2052 ) -> Vec<ImplCandidate<'tcx>> {
2053 let mut candidates: Vec<_> = self
2054 .tcx
2055 .all_impls(trait_pred.def_id())
2056 .filter_map(|def_id| {
2057 let imp = self.tcx.impl_trait_header(def_id);
2058 if imp.polarity != ty::ImplPolarity::Positive
2059 || !self.tcx.is_user_visible_dep(def_id.krate)
2060 {
2061 return None;
2062 }
2063 let imp = imp.trait_ref.skip_binder();
2064
2065 self.fuzzy_match_tys(trait_pred.skip_binder().self_ty(), imp.self_ty(), false).map(
2066 |similarity| ImplCandidate { trait_ref: imp, similarity, impl_def_id: def_id },
2067 )
2068 })
2069 .collect();
2070 if candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
2071 candidates.retain(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. }));
2075 }
2076 candidates
2077 }
2078
2079 pub(super) fn report_similar_impl_candidates(
2080 &self,
2081 impl_candidates: &[ImplCandidate<'tcx>],
2082 obligation: &PredicateObligation<'tcx>,
2083 trait_pred: ty::PolyTraitPredicate<'tcx>,
2084 body_def_id: LocalDefId,
2085 err: &mut Diag<'_>,
2086 other: bool,
2087 param_env: ty::ParamEnv<'tcx>,
2088 ) -> bool {
2089 let parent_map = self.tcx.visible_parent_map(());
2090 let alternative_candidates = |def_id: DefId| {
2091 let mut impl_candidates: Vec<_> = self
2092 .tcx
2093 .all_impls(def_id)
2094 .filter(|def_id| !self.tcx.do_not_recommend_impl(*def_id))
2096 .map(|def_id| (self.tcx.impl_trait_header(def_id), def_id))
2098 .filter_map(|(header, def_id)| {
2099 (header.polarity == ty::ImplPolarity::Positive
2100 || self.tcx.is_automatically_derived(def_id))
2101 .then(|| (header.trait_ref.instantiate_identity().skip_norm_wip(), def_id))
2102 })
2103 .filter(|(trait_ref, _)| {
2104 let self_ty = trait_ref.self_ty();
2105 if let ty::Param(_) = self_ty.kind() {
2107 false
2108 }
2109 else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
2111 let mut did = def.did();
2115 if self.tcx.visibility(did).is_accessible_from(body_def_id, self.tcx) {
2116 if !did.is_local() {
2118 let mut previously_seen_dids: FxHashSet<DefId> = Default::default();
2119 previously_seen_dids.insert(did);
2120 while let Some(&parent) = parent_map.get(&did)
2121 && let hash_set::Entry::Vacant(v) =
2122 previously_seen_dids.entry(parent)
2123 {
2124 if self.tcx.is_doc_hidden(did) {
2125 return false;
2126 }
2127 v.insert();
2128 did = parent;
2129 }
2130 }
2131 true
2132 } else {
2133 false
2134 }
2135 } else {
2136 true
2137 }
2138 })
2139 .collect();
2140
2141 impl_candidates.sort_by_key(|(tr, _)| tr.to_string());
2142 impl_candidates.dedup();
2143 impl_candidates
2144 };
2145
2146 if let [single] = &impl_candidates {
2147 let self_ty = trait_pred.skip_binder().self_ty();
2148 if !self_ty.has_escaping_bound_vars() {
2149 let self_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
2150 if let ty::Ref(_, inner_ty, _) = self_ty.kind()
2151 && self.can_eq(param_env, single.trait_ref.self_ty(), *inner_ty)
2152 && !self.where_clause_expr_matches_failed_self_ty(obligation, self_ty)
2153 {
2154 return true;
2158 }
2159 }
2160
2161 if self.probe(|_| {
2164 let ocx = ObligationCtxt::new(self);
2165
2166 self.enter_forall(trait_pred, |obligation_trait_ref| {
2167 let impl_args = self.fresh_args_for_item(DUMMY_SP, single.impl_def_id);
2168 let impl_trait_ref = ocx.normalize(
2169 &ObligationCause::dummy(),
2170 param_env,
2171 ty::EarlyBinder::bind(self.tcx, single.trait_ref)
2172 .instantiate(self.tcx, impl_args),
2173 );
2174
2175 ocx.register_obligations(
2176 self.tcx
2177 .clauses_of(single.impl_def_id)
2178 .instantiate(self.tcx, impl_args)
2179 .into_iter()
2180 .map(|(clause, _)| {
2181 Obligation::new(
2182 self.tcx,
2183 ObligationCause::dummy(),
2184 param_env,
2185 clause.skip_norm_wip(),
2186 )
2187 }),
2188 );
2189 if !ocx.try_evaluate_obligations().no_errors() {
2190 return false;
2191 }
2192
2193 let mut terrs = ::alloc::vec::Vec::new()vec![];
2194 for (obligation_arg, impl_arg) in
2195 std::iter::zip(obligation_trait_ref.trait_ref.args, impl_trait_ref.args)
2196 {
2197 if (obligation_arg, impl_arg).references_error() {
2198 return false;
2199 }
2200 if let Err(terr) =
2201 ocx.eq(&ObligationCause::dummy(), param_env, impl_arg, obligation_arg)
2202 {
2203 terrs.push(terr);
2204 }
2205 if !ocx.try_evaluate_obligations().no_errors() {
2206 return false;
2207 }
2208 }
2209
2210 if terrs.len() == impl_trait_ref.args.len() {
2212 return false;
2213 }
2214
2215 let impl_trait_ref = self.resolve_vars_if_possible(impl_trait_ref);
2216 if impl_trait_ref.references_error() {
2217 return false;
2218 }
2219
2220 if let [child, ..] = &err.children[..]
2221 && child.level == Level::Help
2222 && let Some(line) = child.messages.get(0)
2223 && let Some(line) = line.0.as_str()
2224 && line.starts_with("the trait")
2225 && line.contains("is not implemented for")
2226 {
2227 err.children.remove(0);
2234 }
2235
2236 let traits = self.cmp_traits(
2237 obligation_trait_ref.def_id(),
2238 &obligation_trait_ref.trait_ref.args[1..],
2239 impl_trait_ref.def_id,
2240 &impl_trait_ref.args[1..],
2241 );
2242 let traits_content = (traits.0.content(), traits.1.content());
2243 let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty());
2244 let types_content = (types.0.content(), types.1.content());
2245 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 `")];
2246 if traits_content.0 == traits_content.1 {
2247 msg.push(StringPart::normal(
2248 impl_trait_ref.print_trait_sugared().to_string(),
2249 ));
2250 } else {
2251 msg.extend(traits.0.0);
2252 }
2253 msg.extend([
2254 StringPart::normal("` "),
2255 StringPart::highlighted("is not"),
2256 StringPart::normal(" implemented for `"),
2257 ]);
2258 if types_content.0 == types_content.1 {
2259 let ty = self
2260 .tcx
2261 .short_string(obligation_trait_ref.self_ty(), err.long_ty_path());
2262 msg.push(StringPart::normal(ty));
2263 } else {
2264 msg.extend(types.0.0);
2265 }
2266 msg.push(StringPart::normal("`"));
2267 if types_content.0 == types_content.1 {
2268 msg.push(StringPart::normal("\nbut trait `"));
2269 msg.extend(traits.1.0);
2270 msg.extend([
2271 StringPart::normal("` "),
2272 StringPart::highlighted("is"),
2273 StringPart::normal(" implemented for it"),
2274 ]);
2275 } else if traits_content.0 == traits_content.1 {
2276 msg.extend([
2277 StringPart::normal("\nbut it "),
2278 StringPart::highlighted("is"),
2279 StringPart::normal(" implemented for `"),
2280 ]);
2281 msg.extend(types.1.0);
2282 msg.push(StringPart::normal("`"));
2283 } else {
2284 msg.push(StringPart::normal("\nbut trait `"));
2285 msg.extend(traits.1.0);
2286 msg.extend([
2287 StringPart::normal("` "),
2288 StringPart::highlighted("is"),
2289 StringPart::normal(" implemented for `"),
2290 ]);
2291 msg.extend(types.1.0);
2292 msg.push(StringPart::normal("`"));
2293 }
2294 err.highlighted_span_help(self.tcx.def_span(single.impl_def_id), msg);
2295
2296 if let [TypeError::Sorts(exp_found)] = &terrs[..] {
2297 let exp_found = self.resolve_vars_if_possible(*exp_found);
2298 let expected =
2299 self.tcx.short_string(exp_found.expected, err.long_ty_path());
2300 let found = self.tcx.short_string(exp_found.found, err.long_ty_path());
2301 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![
2302 StringPart::normal("for that trait implementation, "),
2303 StringPart::normal("expected `"),
2304 StringPart::highlighted(expected),
2305 StringPart::normal("`, found `"),
2306 StringPart::highlighted(found),
2307 StringPart::normal("`"),
2308 ]);
2309 self.suggest_function_pointers_impl(None, &exp_found, err);
2310 }
2311
2312 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2313 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2314 && !crates.is_empty()
2315 {
2316 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2317 err.help("you can use `cargo tree` to explore your dependency tree");
2318 }
2319 true
2320 })
2321 }) {
2322 return true;
2323 }
2324 }
2325
2326 let other = if other { "other " } else { "" };
2327 let report = |mut candidates: Vec<(TraitRef<'tcx>, DefId)>, err: &mut Diag<'_>| {
2328 candidates.retain(|(tr, _)| !tr.references_error());
2329 if candidates.is_empty() {
2330 return false;
2331 }
2332 let mut specific_candidates = candidates.clone();
2333 specific_candidates.retain(|(tr, _)| {
2334 tr.with_replaced_self_ty(self.tcx, trait_pred.skip_binder().self_ty())
2335 == trait_pred.skip_binder().trait_ref
2336 });
2337 if !specific_candidates.is_empty() {
2338 candidates = specific_candidates;
2341 }
2342 if let &[(cand, def_id)] = &candidates[..] {
2343 if self.tcx.is_diagnostic_item(sym::FromResidual, cand.def_id)
2344 && !self.tcx.features().enabled(sym::try_trait_v2)
2345 {
2346 return false;
2347 }
2348 let mut multi_span = MultiSpan::from_span(self.tcx.def_span(def_id));
2349 let (desc, mention_castable) =
2350 match (cand.self_ty().kind(), trait_pred.self_ty().skip_binder().kind()) {
2351 (ty::FnPtr(..), ty::FnDef(..)) => {
2352 (" implemented for fn pointer `", ", cast using `as`")
2353 }
2354 (ty::FnPtr(..), _) => (" implemented for fn pointer `", ""),
2355 _ => {
2356 let evaluate_obligations = || {
2357 let ocx = ObligationCtxt::new_with_diagnostics(self);
2358 self.enter_forall(trait_pred, |obligation_trait_ref| {
2359 let impl_args = self.fresh_args_for_item(DUMMY_SP, def_id);
2360 let impl_trait_ref = ocx.normalize(
2361 &ObligationCause::dummy(),
2362 param_env,
2363 ty::EarlyBinder::bind(self.tcx, cand)
2364 .instantiate(self.tcx, impl_args),
2365 );
2366 if ocx
2367 .eq(
2368 &ObligationCause::dummy(),
2369 param_env,
2370 obligation_trait_ref.trait_ref,
2371 impl_trait_ref,
2372 )
2373 .is_err()
2374 {
2375 return TraitErrors::NoErrors;
2376 }
2377 ocx.register_obligations(
2378 self.tcx
2379 .clauses_of(def_id)
2380 .instantiate(self.tcx, impl_args)
2381 .into_iter()
2382 .map(|(clause, span)| {
2383 Obligation::new(
2384 self.tcx,
2385 ObligationCause::dummy_with_span(span),
2386 param_env,
2387 clause.skip_normalization(),
2388 )
2389 }),
2390 );
2391 ocx.try_evaluate_obligations()
2392 })
2393 };
2394 let failing_obligations =
2395 if !self.tcx.clauses_of(def_id).clauses.is_empty() {
2396 self.probe(|_| evaluate_obligations())
2397 } else {
2398 TraitErrors::NoErrors
2399 };
2400
2401 if failing_obligations.no_errors() {
2402 (" implemented for `", "")
2403 } else {
2404 for error in failing_obligations {
2405 multi_span.push_span_label(
2406 error.root_obligation.cause.span,
2407 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unsatisfied requirement introduced here: `{0}`",
error.root_obligation.predicate))
})format!(
2408 "unsatisfied requirement introduced here: `{}`",
2409 error.root_obligation.predicate,
2410 ),
2411 );
2412 }
2413
2414 (" conditionally implemented for `", "")
2415 }
2416 }
2417 };
2418 let trait_ = self.tcx.short_string(cand.print_trait_sugared(), err.long_ty_path());
2419 let self_ty = self.tcx.short_string(cand.self_ty(), err.long_ty_path());
2420 err.highlighted_span_help(
2421 multi_span,
2422 ::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![
2423 StringPart::normal(format!("the trait `{trait_}` ")),
2424 StringPart::highlighted("is"),
2425 StringPart::normal(desc),
2426 StringPart::highlighted(self_ty),
2427 StringPart::normal("`"),
2428 StringPart::normal(mention_castable),
2429 ],
2430 );
2431 return true;
2432 }
2433 let trait_ref = TraitRef::identity(self.tcx, candidates[0].0.def_id);
2434 let mut traits: Vec<_> =
2436 candidates.iter().map(|(c, _)| c.print_only_trait_path().to_string()).collect();
2437 traits.sort();
2438 traits.dedup();
2439 let all_traits_equal = traits.len() == 1;
2442 let mut types: Vec<_> =
2443 candidates.iter().map(|(c, _)| c.self_ty().to_string()).collect();
2444 types.sort();
2445 types.dedup();
2446 let all_types_equal = types.len() == 1;
2447
2448 let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose {
2449 candidates.len()
2450 } else {
2451 8
2452 };
2453 if candidates.len() < 5 {
2454 let spans: Vec<_> =
2455 candidates.iter().map(|&(_, def_id)| self.tcx.def_span(def_id)).collect();
2456 let mut span: MultiSpan = spans.into();
2457 for (c, def_id) in &candidates {
2458 let msg = if all_traits_equal {
2459 ::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()))
2460 } else if all_types_equal {
2461 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2462 "`{}`",
2463 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path())
2464 )
2465 } else {
2466 ::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!(
2467 "`{}` implements `{}`",
2468 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2469 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path()),
2470 )
2471 };
2472 span.push_span_label(self.tcx.def_span(*def_id), msg);
2473 }
2474 let msg = if all_types_equal {
2475 ::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!(
2476 "`{}` implements trait `{}`",
2477 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2478 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2479 )
2480 } else {
2481 ::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!(
2482 "the following {other}types implement trait `{}`",
2483 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2484 )
2485 };
2486 err.span_help(span, msg);
2487 } else {
2488 let mut tuple_min_arity = usize::MAX;
2494 let mut tuple_max_arity = 0_usize;
2495 let mut last_arity = None;
2496 let mut all_types_tuples_cont_arity = true;
2497 candidates.sort_by(|(c1, _), (c2, _)| {
2498 if let ty::Tuple(tys1) = c1.self_ty().kind()
2499 && let ty::Tuple(tys2) = c2.self_ty().kind()
2500 {
2501 tys1.len().cmp(&tys2.len())
2502 } else {
2503 std::cmp::Ordering::Equal
2504 }
2505 });
2506 let candidate_names: Vec<String> = candidates
2507 .iter()
2508 .map(|(c, _)| {
2509 if all_traits_equal {
2510 if all_types_tuples_cont_arity
2511 && let ty::Tuple(tys) = c.self_ty().kind()
2512 && last_arity.map_or(1, |a: usize| a.abs_diff(tys.len())) == 1
2513 {
2514 last_arity = Some(tys.len());
2515 if tys.len() > tuple_max_arity {
2516 tuple_max_arity = tys.len();
2517 }
2518 if tys.len() < tuple_min_arity {
2519 tuple_min_arity = tys.len();
2520 }
2521 } else {
2522 all_types_tuples_cont_arity = false;
2523 }
2524 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n {0}",
self.tcx.short_string(c.self_ty(), err.long_ty_path())))
})format!(
2525 "\n {}",
2526 self.tcx.short_string(c.self_ty(), err.long_ty_path())
2527 )
2528 } else if all_types_equal {
2529 ::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!(
2530 "\n {}",
2531 self.tcx
2532 .short_string(c.print_only_trait_path(), err.long_ty_path())
2533 )
2534 } else {
2535 ::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!(
2536 "\n `{}` implements `{}`",
2537 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2538 self.tcx
2539 .short_string(c.print_only_trait_path(), err.long_ty_path()),
2540 )
2541 }
2542 })
2543 .collect();
2544
2545 let details = if all_traits_equal && all_types_tuples_cont_arity {
2546 if tuple_min_arity == 0 {
2547 ::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}")
2548 } else {
2549 ::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!(
2550 "for tuples of arity {tuple_min_arity} up to and including {tuple_max_arity}"
2551 )
2552 }
2553 } else {
2554 String::new()
2555 };
2556 let (candidate_names, end) = if all_traits_equal && all_types_tuples_cont_arity {
2557 (
2558 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n (T₁, T₂, …, Tₙ) {0}",
details))
})]))vec![
2559 format!("\n (T\u{2081}, T\u{2082}, …, T\u{2099}) {details}"),
2561 ],
2562 1,
2563 )
2564 } else {
2565 (candidate_names, end)
2566 };
2567 let msg = if all_types_equal {
2568 ::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!(
2569 "`{}` implements trait `{}`",
2570 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2571 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2572 )
2573 } else {
2574 ::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!(
2575 "the following {other}types implement trait `{}`",
2576 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2577 )
2578 };
2579
2580 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!(
2581 "{msg}:{}{}",
2582 candidate_names[..end].join(""),
2583 if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
2584 format!("\nand {} others", candidates.len() - 8)
2585 } else {
2586 String::new()
2587 }
2588 ));
2589 }
2590
2591 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2592 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2593 && !crates.is_empty()
2594 {
2595 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2596 err.help("you can use `cargo tree` to explore your dependency tree");
2597 }
2598 true
2599 };
2600
2601 let impl_candidates = impl_candidates
2604 .into_iter()
2605 .cloned()
2606 .filter(|cand| !self.tcx.do_not_recommend_impl(cand.impl_def_id))
2607 .collect::<Vec<_>>();
2608
2609 let def_id = trait_pred.def_id();
2610 if impl_candidates.is_empty() {
2611 if self.tcx.trait_is_auto(def_id)
2612 || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2613 || self.tcx.get_diagnostic_name(def_id).is_some()
2614 {
2615 return false;
2617 }
2618 return report(alternative_candidates(def_id), err);
2619 }
2620
2621 let mut impl_candidates: Vec<_> = impl_candidates
2628 .iter()
2629 .cloned()
2630 .filter(|cand| !cand.trait_ref.references_error())
2631 .map(|mut cand| {
2632 cand.trait_ref = self
2636 .tcx
2637 .try_normalize_erasing_regions(
2638 ty::TypingEnv::non_body_analysis(self.tcx, cand.impl_def_id),
2639 Unnormalized::new_wip(cand.trait_ref),
2640 )
2641 .unwrap_or(cand.trait_ref);
2642 cand
2643 })
2644 .collect();
2645 impl_candidates.sort_by_key(|cand| {
2646 let len = if let GenericArgKind::Type(ty) = cand.trait_ref.args[0].kind()
2648 && let ty::Array(_, len) = ty.kind()
2649 {
2650 len.try_to_target_usize(self.tcx).unwrap_or(u64::MAX)
2652 } else {
2653 0
2654 };
2655
2656 (cand.similarity, len, cand.trait_ref.to_string())
2657 });
2658 let mut impl_candidates: Vec<_> =
2659 impl_candidates.into_iter().map(|cand| (cand.trait_ref, cand.impl_def_id)).collect();
2660 impl_candidates.dedup();
2661
2662 report(impl_candidates, err)
2663 }
2664
2665 fn report_similar_impl_candidates_for_root_obligation(
2666 &self,
2667 obligation: &PredicateObligation<'tcx>,
2668 trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2669 body_def_id: LocalDefId,
2670 err: &mut Diag<'_>,
2671 ) {
2672 let mut code = obligation.cause.code();
2679 let mut trait_pred = trait_predicate;
2680 let mut peeled = false;
2681 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
2682 code = parent_code;
2683 if let Some(parent_trait_pred) = parent_trait_pred {
2684 trait_pred = parent_trait_pred;
2685 peeled = true;
2686 }
2687 }
2688 let def_id = trait_pred.def_id();
2689 if peeled && !self.tcx.trait_is_auto(def_id) && self.tcx.as_lang_item(def_id).is_none() {
2695 let impl_candidates = self.find_similar_impl_candidates(trait_pred);
2696 self.report_similar_impl_candidates(
2697 &impl_candidates,
2698 obligation,
2699 trait_pred,
2700 body_def_id,
2701 err,
2702 true,
2703 obligation.param_env,
2704 );
2705 }
2706 }
2707
2708 fn get_parent_trait_ref(
2710 &self,
2711 code: &ObligationCauseCode<'tcx>,
2712 ) -> Option<(Ty<'tcx>, Option<Span>)> {
2713 match code {
2714 ObligationCauseCode::BuiltinDerived(data) => {
2715 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2716 match self.get_parent_trait_ref(&data.parent_code) {
2717 Some(t) => Some(t),
2718 None => {
2719 let ty = parent_trait_ref.skip_binder().self_ty();
2720 let span = TyCategory::from_ty(self.tcx, ty)
2721 .map(|(_, def_id)| self.tcx.def_span(def_id));
2722 Some((ty, span))
2723 }
2724 }
2725 }
2726 ObligationCauseCode::FunctionArg { parent_code, .. } => {
2727 self.get_parent_trait_ref(parent_code)
2728 }
2729 _ => None,
2730 }
2731 }
2732
2733 fn check_same_trait_different_version(
2734 &self,
2735 err: &mut Diag<'_>,
2736 trait_pred: ty::PolyTraitPredicate<'tcx>,
2737 ) -> bool {
2738 let get_trait_impls = |trait_def_id| {
2739 let mut trait_impls = ::alloc::vec::Vec::new()vec![];
2740 self.tcx.for_each_relevant_impl(
2741 trait_def_id,
2742 trait_pred.skip_binder().self_ty(),
2743 |impl_def_id| {
2744 let impl_trait_header = self.tcx.impl_trait_header(impl_def_id);
2745 trait_impls
2746 .push(self.tcx.def_span(impl_trait_header.trait_ref.skip_binder().def_id));
2747 },
2748 );
2749 trait_impls
2750 };
2751 self.check_same_definition_different_crate(
2752 err,
2753 trait_pred.def_id(),
2754 self.tcx.visible_traits(),
2755 get_trait_impls,
2756 "trait",
2757 )
2758 }
2759
2760 pub fn note_two_crate_versions(
2761 &self,
2762 krate: CrateNum,
2763 sp: impl Into<MultiSpan>,
2764 err: &mut Diag<'_>,
2765 ) {
2766 let crate_name = self.tcx.crate_name(krate);
2767 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!(
2768 "there are multiple different versions of crate `{crate_name}` in the dependency graph"
2769 );
2770 err.span_note(sp, crate_msg);
2771 }
2772
2773 fn note_adt_version_mismatch(
2774 &self,
2775 err: &mut Diag<'_>,
2776 trait_pred: ty::PolyTraitPredicate<'tcx>,
2777 ) {
2778 let ty::Adt(impl_self_def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2779 else {
2780 return;
2781 };
2782
2783 let impl_self_did = impl_self_def.did();
2784
2785 if impl_self_did.krate == LOCAL_CRATE {
2788 return;
2789 }
2790
2791 let impl_self_path = self.comparable_path(impl_self_did);
2792 let impl_self_crate_name = self.tcx.crate_name(impl_self_did.krate);
2793 let similar_items: UnordSet<_> = self
2794 .tcx
2795 .visible_parent_map(())
2796 .items()
2797 .filter_map(|(&item, _)| {
2798 if impl_self_did == item {
2800 return None;
2801 }
2802 if item.krate == LOCAL_CRATE {
2805 return None;
2806 }
2807 if impl_self_crate_name != self.tcx.crate_name(item.krate) {
2810 return None;
2811 }
2812 if !self.tcx.def_kind(item).is_adt() {
2815 return None;
2816 }
2817 let path = self.comparable_path(item);
2818 let is_similar = path.ends_with(&impl_self_path) || impl_self_path.ends_with(&path);
2821 is_similar.then_some((item, path))
2822 })
2823 .collect();
2824
2825 let mut similar_items =
2826 similar_items.into_items().into_sorted_stable_ord_by_key(|(_, path)| path);
2827 similar_items.dedup();
2828
2829 for (similar_item, _) in similar_items {
2830 err.span_help(self.tcx.def_span(similar_item), "item with same name found");
2831 self.note_two_crate_versions(similar_item.krate, MultiSpan::new(), err);
2832 }
2833 }
2834
2835 fn check_same_name_different_path(
2836 &self,
2837 err: &mut Diag<'_>,
2838 obligation: &PredicateObligation<'tcx>,
2839 trait_pred: ty::PolyTraitPredicate<'tcx>,
2840 ) -> bool {
2841 let mut suggested = false;
2842 let trait_def_id = trait_pred.def_id();
2843 let trait_has_same_params = |other_trait_def_id: DefId| -> bool {
2844 let trait_generics = self.tcx.generics_of(trait_def_id);
2845 let other_trait_generics = self.tcx.generics_of(other_trait_def_id);
2846
2847 if trait_generics.count() != other_trait_generics.count() {
2848 return false;
2849 }
2850 trait_generics.own_params.iter().zip(other_trait_generics.own_params.iter()).all(
2851 |(a, b)| match (&a.kind, &b.kind) {
2852 (ty::GenericParamDefKind::Lifetime, ty::GenericParamDefKind::Lifetime)
2853 | (
2854 ty::GenericParamDefKind::Type { .. },
2855 ty::GenericParamDefKind::Type { .. },
2856 )
2857 | (
2858 ty::GenericParamDefKind::Const { .. },
2859 ty::GenericParamDefKind::Const { .. },
2860 ) => true,
2861 _ => false,
2862 },
2863 )
2864 };
2865 let trait_name = self.tcx.item_name(trait_def_id);
2866 if let Some(other_trait_def_id) = self.tcx.all_traits_including_private().find(|&def_id| {
2867 trait_def_id != def_id
2868 && trait_name == self.tcx.item_name(def_id)
2869 && trait_has_same_params(def_id)
2870 && !self.tcx.is_lang_item(def_id, LangItem::PointeeSized)
2872 && self.predicate_must_hold_modulo_regions(&Obligation::new(
2873 self.tcx,
2874 obligation.cause.clone(),
2875 obligation.param_env,
2876 trait_pred.map_bound(|tr| ty::TraitPredicate {
2877 trait_ref: ty::TraitRef::new(self.tcx, def_id, tr.trait_ref.args),
2878 ..tr
2879 }),
2880 ))
2881 }) {
2882 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!(
2883 "`{}` implements similarly named trait `{}`, but not `{}`",
2884 trait_pred.self_ty(),
2885 self.tcx.def_path_str(other_trait_def_id),
2886 trait_pred.print_modifiers_and_trait_path()
2887 ));
2888 suggested = true;
2889 }
2890 suggested
2891 }
2892
2893 pub fn note_different_trait_with_same_name(
2898 &self,
2899 err: &mut Diag<'_>,
2900 obligation: &PredicateObligation<'tcx>,
2901 trait_pred: ty::PolyTraitPredicate<'tcx>,
2902 ) -> bool {
2903 if self.check_same_trait_different_version(err, trait_pred) {
2904 return true;
2905 }
2906 self.check_same_name_different_path(err, obligation, trait_pred)
2907 }
2908
2909 fn comparable_path(&self, did: DefId) -> String {
2912 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}",
self.tcx.def_path_str(did)))
})format!("::{}", self.tcx.def_path_str(did))
2913 }
2914
2915 pub(super) fn mk_trait_obligation_with_new_self_ty(
2920 &self,
2921 param_env: ty::ParamEnv<'tcx>,
2922 trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
2923 ) -> PredicateObligation<'tcx> {
2924 let trait_pred = trait_ref_and_ty
2925 .map_bound(|(tr, new_self_ty)| tr.with_replaced_self_ty(self.tcx, new_self_ty));
2926
2927 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
2928 }
2929
2930 fn predicate_can_apply(
2933 &self,
2934 param_env: ty::ParamEnv<'tcx>,
2935 pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + TypeFoldable<TyCtxt<'tcx>>,
2936 ) -> bool {
2937 struct ParamToVarFolder<'a, 'tcx> {
2938 infcx: &'a InferCtxt<'tcx>,
2939 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2940 }
2941
2942 impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
2943 fn cx(&self) -> TyCtxt<'tcx> {
2944 self.infcx.tcx
2945 }
2946
2947 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2951 match ty.kind() {
2952 ty::Param(_) => {
2953 let infcx = self.infcx;
2954 *self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
2955 }
2956 &ty::Alias(is_rigid, alias)
2960 if is_rigid == ty::IsRigid::Yes
2961 && ty.has_type_flags(ty::TypeFlags::HAS_TY_PARAM) =>
2962 {
2963 let alias = alias.fold_with(self);
2964 Ty::new_alias(self.cx(), ty::IsRigid::No, alias)
2965 }
2966 _ => ty.super_fold_with(self),
2967 }
2968 }
2969 }
2970
2971 self.probe(|_| {
2972 let cleaned_pred =
2973 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2974
2975 let InferOk { value: cleaned_pred, .. } = self
2976 .infcx
2977 .at(&ObligationCause::dummy(), param_env)
2978 .normalize(Unnormalized::new_wip(cleaned_pred));
2979
2980 let obligation =
2981 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
2982
2983 self.predicate_may_hold(&obligation)
2984 })
2985 }
2986
2987 pub fn note_obligation_cause(
2988 &self,
2989 err: &mut Diag<'_>,
2990 obligation: &PredicateObligation<'tcx>,
2991 ) {
2992 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2995 self.note_obligation_cause_code(
2996 obligation.cause.body_def_id,
2997 err,
2998 obligation.predicate,
2999 obligation.param_env,
3000 obligation.cause.code(),
3001 &mut ::alloc::vec::Vec::new()vec![],
3002 &mut Default::default(),
3003 );
3004 self.suggest_swapping_lhs_and_rhs(
3005 err,
3006 obligation.predicate,
3007 obligation.param_env,
3008 obligation.cause.code(),
3009 );
3010 self.suggest_borrow_for_unsized_closure_return(
3011 obligation.cause.body_def_id,
3012 err,
3013 obligation.predicate,
3014 );
3015 self.suggest_unsized_bound_if_applicable(err, obligation);
3016 if let Some(span) = err.span.primary_span()
3017 && let Some(mut diag) =
3018 self.dcx().steal_non_err(span, StashKey::AssociatedTypeSuggestion)
3019 && let Suggestions::Enabled(ref mut s1) = err.suggestions
3020 && let Suggestions::Enabled(ref mut s2) = diag.suggestions
3021 {
3022 s1.append(s2);
3023 diag.cancel()
3024 }
3025 }
3026 }
3027
3028 pub(super) fn is_recursive_obligation(
3029 &self,
3030 obligated_types: &mut Vec<Ty<'tcx>>,
3031 cause_code: &ObligationCauseCode<'tcx>,
3032 ) -> bool {
3033 if let ObligationCauseCode::BuiltinDerived(data) = cause_code {
3034 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
3035 let self_ty = parent_trait_ref.skip_binder().self_ty();
3036 if obligated_types.iter().any(|ot| ot == &self_ty) {
3037 return true;
3038 }
3039 if let ty::Adt(def, args) = self_ty.kind()
3040 && let [arg] = &args[..]
3041 && let ty::GenericArgKind::Type(ty) = arg.kind()
3042 && let ty::Adt(inner_def, _) = ty.kind()
3043 && inner_def == def
3044 {
3045 return true;
3046 }
3047 }
3048 false
3049 }
3050
3051 fn get_standard_error_message(
3052 &self,
3053 trait_predicate: ty::PolyTraitPredicate<'tcx>,
3054 predicate_constness: Option<ty::BoundConstness>,
3055 post_message: String,
3056 long_ty_path: &mut Option<PathBuf>,
3057 ) -> String {
3058 ::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!(
3059 "the trait bound `{}` is not satisfied{post_message}",
3060 self.tcx.short_string(
3061 trait_predicate.print_with_bound_constness(predicate_constness),
3062 long_ty_path,
3063 ),
3064 )
3065 }
3066
3067 fn select_transmute_obligation_for_reporting(
3068 &self,
3069 obligation: &PredicateObligation<'tcx>,
3070 trait_predicate: ty::PolyTraitPredicate<'tcx>,
3071 root_obligation: &PredicateObligation<'tcx>,
3072 ) -> (PredicateObligation<'tcx>, ty::PolyTraitPredicate<'tcx>) {
3073 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
3074 return (obligation.clone(), trait_predicate);
3075 }
3076
3077 let ocx = ObligationCtxt::new(self);
3078 let normalized_predicate = self.tcx.erase_and_anonymize_regions(
3079 self.tcx.instantiate_bound_regions_with_erased(trait_predicate),
3080 );
3081 let trait_ref = normalized_predicate.trait_ref;
3082
3083 let assume = ocx.normalize(
3084 &obligation.cause,
3085 obligation.param_env,
3086 Unnormalized::new_wip(trait_ref.args.const_at(2)),
3087 );
3088
3089 let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
3090 return (obligation.clone(), trait_predicate);
3091 };
3092
3093 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) {
rustc_transmute::Answer::Yes => true,
_ => false,
}matches!(
3094 rustc_transmute::TransmuteTypeEnv::new(self.tcx).is_transmutable(
3095 trait_ref.args.type_at(1),
3096 trait_ref.args.type_at(0),
3097 assume,
3098 ),
3099 rustc_transmute::Answer::Yes,
3100 );
3101
3102 if is_normalized_yes
3104 && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3105 root_obligation.predicate.kind().skip_binder()
3106 && root_pred.def_id() == trait_predicate.def_id()
3107 {
3108 return (root_obligation.clone(), root_obligation.predicate.kind().rebind(root_pred));
3109 }
3110
3111 (obligation.clone(), trait_predicate)
3112 }
3113
3114 fn get_safe_transmute_error_and_reason(
3115 &self,
3116 obligation: PredicateObligation<'tcx>,
3117 trait_pred: ty::PolyTraitPredicate<'tcx>,
3118 span: Span,
3119 ) -> GetSafeTransmuteErrorAndReason {
3120 use rustc_transmute::Answer;
3121 self.probe(|_| {
3122 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
3125 return GetSafeTransmuteErrorAndReason::Default;
3126 }
3127
3128 let trait_pred = self.tcx.erase_and_anonymize_regions(
3130 self.tcx.instantiate_bound_regions_with_erased(trait_pred),
3131 );
3132
3133 let ocx = ObligationCtxt::new(self);
3134 let assume = ocx.normalize(
3135 &obligation.cause,
3136 obligation.param_env,
3137 Unnormalized::new_wip(trait_pred.trait_ref.args.const_at(2)),
3138 );
3139
3140 let Some(assume) = rustc_transmute::Assume::from_const(self.infcx.tcx, assume) else {
3141 self.dcx().span_delayed_bug(
3142 span,
3143 "Unable to construct rustc_transmute::Assume where it was previously possible",
3144 );
3145 return GetSafeTransmuteErrorAndReason::Silent;
3146 };
3147
3148 let dst = trait_pred.trait_ref.args.type_at(0);
3149 let src = trait_pred.trait_ref.args.type_at(1);
3150 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}`");
3151
3152 match rustc_transmute::TransmuteTypeEnv::new(self.infcx.tcx)
3153 .is_transmutable(src, dst, assume)
3154 {
3155 Answer::No(reason) => {
3156 let safe_transmute_explanation = match reason {
3157 rustc_transmute::Reason::SrcIsNotYetSupported => {
3158 ::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")
3159 }
3160 rustc_transmute::Reason::DstIsNotYetSupported => {
3161 ::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")
3162 }
3163 rustc_transmute::Reason::DstIsBitIncompatible => {
3164 ::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!(
3165 "at least one value of `{src}` isn't a bit-valid value of `{dst}`"
3166 )
3167 }
3168 rustc_transmute::Reason::DstUninhabited => {
3169 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is uninhabited", dst))
})format!("`{dst}` is uninhabited")
3170 }
3171 rustc_transmute::Reason::DstMayHaveSafetyInvariants => {
3172 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` may carry safety invariants",
dst))
})format!("`{dst}` may carry safety invariants")
3173 }
3174 rustc_transmute::Reason::DstIsTooBig => {
3175 ::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}`")
3176 }
3177 rustc_transmute::Reason::DstRefIsTooBig {
3178 src,
3179 src_size,
3180 dst,
3181 dst_size,
3182 } => {
3183 ::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!(
3184 "the size of `{src}` ({src_size} bytes) \
3185 is smaller than that of `{dst}` ({dst_size} bytes)"
3186 )
3187 }
3188 rustc_transmute::Reason::SrcSizeOverflow => {
3189 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
src))
})format!(
3190 "values of the type `{src}` are too big for the target architecture"
3191 )
3192 }
3193 rustc_transmute::Reason::DstSizeOverflow => {
3194 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
dst))
})format!(
3195 "values of the type `{dst}` are too big for the target architecture"
3196 )
3197 }
3198 rustc_transmute::Reason::DstHasStricterAlignment {
3199 src_min_align,
3200 dst_min_align,
3201 } => {
3202 ::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!(
3203 "the minimum alignment of `{src}` ({src_min_align}) should be \
3204 greater than that of `{dst}` ({dst_min_align})"
3205 )
3206 }
3207 rustc_transmute::Reason::DstIsMoreUnique => {
3208 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is a shared reference, but `{1}` is a unique reference",
src, dst))
})format!(
3209 "`{src}` is a shared reference, but `{dst}` is a unique reference"
3210 )
3211 }
3212 rustc_transmute::Reason::TypeError => {
3214 return GetSafeTransmuteErrorAndReason::Silent;
3215 }
3216 rustc_transmute::Reason::SrcLayoutUnknown => {
3217 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", src))
})format!("`{src}` has an unknown layout")
3218 }
3219 rustc_transmute::Reason::DstLayoutUnknown => {
3220 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", dst))
})format!("`{dst}` has an unknown layout")
3221 }
3222 };
3223 GetSafeTransmuteErrorAndReason::Error {
3224 err_msg,
3225 safe_transmute_explanation: Some(safe_transmute_explanation),
3226 }
3227 }
3228 Answer::Yes => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("Inconsistent rustc_transmute::is_transmutable(...) result, got Yes"))span_bug!(
3230 span,
3231 "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
3232 ),
3233 Answer::If(_) => GetSafeTransmuteErrorAndReason::Error {
3238 err_msg,
3239 safe_transmute_explanation: None,
3240 },
3241 }
3242 })
3243 }
3244
3245 fn find_explicit_cast_type(
3248 &self,
3249 param_env: ty::ParamEnv<'tcx>,
3250 found_ty: Ty<'tcx>,
3251 self_ty: Ty<'tcx>,
3252 ) -> Option<Ty<'tcx>> {
3253 let ty::Ref(region, inner_ty, mutbl) = *found_ty.kind() else {
3254 return None;
3255 };
3256
3257 let mut derefs = (self.autoderef_steps)(inner_ty).into_iter();
3258 derefs.next(); let deref_target = derefs.into_iter().next()?.0;
3260
3261 let cast_ty = Ty::new_ref(self.tcx, region, deref_target, mutbl);
3262
3263 let Some(from_def_id) = self.tcx.get_diagnostic_item(sym::From) else {
3264 return None;
3265 };
3266 let Some(try_from_def_id) = self.tcx.get_diagnostic_item(sym::TryFrom) else {
3267 return None;
3268 };
3269
3270 if self.has_impl_for_type(
3271 param_env,
3272 ty::TraitRef::new(
3273 self.tcx,
3274 from_def_id,
3275 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3276 ),
3277 ) {
3278 Some(cast_ty)
3279 } else if self.has_impl_for_type(
3280 param_env,
3281 ty::TraitRef::new(
3282 self.tcx,
3283 try_from_def_id,
3284 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3285 ),
3286 ) {
3287 Some(cast_ty)
3288 } else {
3289 None
3290 }
3291 }
3292
3293 fn has_impl_for_type(
3294 &self,
3295 param_env: ty::ParamEnv<'tcx>,
3296 trait_ref: ty::TraitRef<'tcx>,
3297 ) -> bool {
3298 let obligation = Obligation::new(
3299 self.tcx,
3300 ObligationCause::dummy(),
3301 param_env,
3302 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive },
3303 );
3304
3305 self.predicate_must_hold_modulo_regions(&obligation)
3306 }
3307
3308 fn add_tuple_trait_message(
3309 &self,
3310 obligation_cause_code: &ObligationCauseCode<'tcx>,
3311 err: &mut Diag<'_>,
3312 ) {
3313 match obligation_cause_code {
3314 ObligationCauseCode::RustCall => {
3315 err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
3316 }
3317 ObligationCauseCode::WhereClause(def_id, _) if self.tcx.is_fn_trait(*def_id) => {
3318 err.code(E0059);
3319 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!(
3320 "type parameter to bare `{}` trait must be a tuple",
3321 self.tcx.def_path_str(*def_id)
3322 ));
3323 }
3324 _ => {}
3325 }
3326 }
3327
3328 fn try_to_add_help_message(
3329 &self,
3330 root_obligation: &PredicateObligation<'tcx>,
3331 obligation: &PredicateObligation<'tcx>,
3332 trait_predicate: ty::PolyTraitPredicate<'tcx>,
3333 err: &mut Diag<'_>,
3334 span: Span,
3335 is_fn_trait: bool,
3336 suggested: bool,
3337 ) {
3338 let body_def_id = obligation.cause.body_def_id;
3339 let span = if let ObligationCauseCode::BinOp { rhs_span, .. } = obligation.cause.code() {
3340 *rhs_span
3341 } else {
3342 span
3343 };
3344
3345 let trait_def_id = trait_predicate.def_id();
3347 if is_fn_trait
3348 && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
3349 obligation.param_env,
3350 trait_predicate.self_ty(),
3351 trait_predicate.skip_binder().polarity,
3352 )
3353 {
3354 self.add_help_message_for_fn_trait(trait_predicate, err, implemented_kind, params);
3355 } else if !trait_predicate.has_non_region_infer()
3356 && self.predicate_can_apply(obligation.param_env, trait_predicate)
3357 {
3358 self.suggest_restricting_param_bound(
3366 err,
3367 trait_predicate,
3368 None,
3369 obligation.cause.body_def_id,
3370 );
3371 } else if trait_def_id.is_local()
3372 && self.tcx.trait_impls_of(trait_def_id).is_empty()
3373 && !self.tcx.trait_is_auto(trait_def_id)
3374 && !self.tcx.trait_is_alias(trait_def_id)
3375 && trait_predicate.polarity() == ty::PredicatePolarity::Positive
3376 {
3377 err.span_help(
3378 self.tcx.def_span(trait_def_id),
3379 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"),
3380 );
3381 } else if !suggested && trait_predicate.polarity() == ty::PredicatePolarity::Positive {
3382 let impl_candidates = self.find_similar_impl_candidates(trait_predicate);
3384 if !self.report_similar_impl_candidates(
3385 &impl_candidates,
3386 obligation,
3387 trait_predicate,
3388 body_def_id,
3389 err,
3390 true,
3391 obligation.param_env,
3392 ) {
3393 self.report_similar_impl_candidates_for_root_obligation(
3394 obligation,
3395 trait_predicate,
3396 body_def_id,
3397 err,
3398 );
3399 }
3400
3401 self.suggest_convert_to_slice(
3402 err,
3403 obligation,
3404 trait_predicate,
3405 impl_candidates.as_slice(),
3406 span,
3407 );
3408
3409 self.suggest_tuple_wrapping(err, root_obligation, obligation);
3410 }
3411 self.suggest_shadowed_inherent_method(err, obligation, trait_predicate);
3412 }
3413
3414 fn add_help_message_for_fn_trait(
3415 &self,
3416 trait_pred: ty::PolyTraitPredicate<'tcx>,
3417 err: &mut Diag<'_>,
3418 implemented_kind: ty::ClosureKind,
3419 params: ty::Binder<'tcx, Ty<'tcx>>,
3420 ) {
3421 let selected_kind = self
3428 .tcx
3429 .fn_trait_kind_from_def_id(trait_pred.def_id())
3430 .expect("expected to map DefId to ClosureKind");
3431 if !implemented_kind.extends(selected_kind) {
3432 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!(
3433 "`{}` implements `{}`, but it must implement `{}`, which is more general",
3434 trait_pred.skip_binder().self_ty(),
3435 implemented_kind,
3436 selected_kind
3437 ));
3438 }
3439
3440 let ty::Tuple(given) = *params.skip_binder().kind() else {
3442 return;
3443 };
3444
3445 let expected_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
3446 let ty::Tuple(expected) = *expected_ty.kind() else {
3447 return;
3448 };
3449
3450 if expected.len() != given.len() {
3451 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",
given.len(), if given.len() == 1 { "" } else { "s" },
expected.len(), if expected.len() == 1 { "" } else { "s" }))
})format!(
3453 "expected a closure taking {} argument{}, but one taking {} argument{} was given",
3454 given.len(),
3455 pluralize!(given.len()),
3456 expected.len(),
3457 pluralize!(expected.len()),
3458 ));
3459 return;
3460 }
3461
3462 let given_ty = Ty::new_fn_ptr(
3463 self.tcx,
3464 params.rebind(self.tcx.mk_fn_sig_safe_rust_abi(given, self.tcx.types.unit)),
3465 );
3466 let expected_ty = Ty::new_fn_ptr(
3467 self.tcx,
3468 trait_pred.rebind(self.tcx.mk_fn_sig_safe_rust_abi(expected, self.tcx.types.unit)),
3469 );
3470
3471 if !self.same_type_modulo_infer(given_ty, expected_ty) {
3472 let (expected_args, given_args) = self.cmp(expected_ty, given_ty);
3474 err.note_expected_found(
3475 "a closure with signature",
3476 expected_args,
3477 "a closure with signature",
3478 given_args,
3479 );
3480 }
3481 }
3482
3483 fn report_closure_error(
3484 &self,
3485 obligation: &PredicateObligation<'tcx>,
3486 closure_def_id: DefId,
3487 found_kind: ty::ClosureKind,
3488 kind: ty::ClosureKind,
3489 trait_prefix: &'static str,
3490 ) -> Diag<'a> {
3491 let closure_span = self.tcx.def_span(closure_def_id);
3492
3493 let mut err = ClosureKindMismatch {
3494 closure_span,
3495 expected: kind,
3496 found: found_kind,
3497 cause_span: obligation.cause.span,
3498 trait_prefix,
3499 fn_once_label: None,
3500 fn_mut_label: None,
3501 };
3502
3503 if let Some(typeck_results) = &self.typeck_results {
3506 let hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id.expect_local());
3507 match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
3508 (ty::ClosureKind::FnOnce, Some((span, place))) => {
3509 err.fn_once_label = Some(ClosureFnOnceLabel {
3510 span: *span,
3511 place: ty::place_to_string_for_capture(self.tcx, place),
3512 trait_prefix,
3513 })
3514 }
3515 (ty::ClosureKind::FnMut, Some((span, place))) => {
3516 err.fn_mut_label = Some(ClosureFnMutLabel {
3517 span: *span,
3518 place: ty::place_to_string_for_capture(self.tcx, place),
3519 trait_prefix,
3520 })
3521 }
3522 _ => {}
3523 }
3524 }
3525
3526 self.dcx().create_err(err)
3527 }
3528
3529 fn report_cyclic_signature_error(
3530 &self,
3531 obligation: &PredicateObligation<'tcx>,
3532 found_trait_ref: ty::TraitRef<'tcx>,
3533 expected_trait_ref: ty::TraitRef<'tcx>,
3534 terr: TypeError<'tcx>,
3535 ) -> Diag<'a> {
3536 let self_ty = found_trait_ref.self_ty();
3537 let (cause, terr) = if let ty::Closure(def_id, _) = *self_ty.kind() {
3538 (
3539 ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
3540 TypeError::CyclicTy(self_ty),
3541 )
3542 } else {
3543 (obligation.cause.clone(), terr)
3544 };
3545 self.report_and_explain_type_error(
3546 TypeTrace::trait_refs(&cause, expected_trait_ref, found_trait_ref),
3547 obligation.param_env,
3548 terr,
3549 )
3550 }
3551
3552 fn report_signature_mismatch_error(
3553 &self,
3554 obligation: &PredicateObligation<'tcx>,
3555 span: Span,
3556 found_trait_ref: ty::TraitRef<'tcx>,
3557 expected_trait_ref: ty::TraitRef<'tcx>,
3558 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3559 let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
3560 let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
3561
3562 expected_trait_ref.self_ty().error_reported()?;
3563 let found_trait_ty = found_trait_ref.self_ty();
3564
3565 let found_did = match *found_trait_ty.kind() {
3566 ty::Closure(did, _) | ty::FnDef(did, _) | ty::Coroutine(did, ..) => Some(did),
3567 _ => None,
3568 };
3569
3570 let found_node = found_did.and_then(|did| self.tcx.hir_get_if_local(did));
3571 let found_span = found_did.and_then(|did| self.tcx.hir_span_if_local(did));
3572
3573 if !self.reported_signature_mismatch.borrow_mut().insert((span, found_span)) {
3574 return Err(self.dcx().span_delayed_bug(span, "already_reported"));
3577 }
3578
3579 let mut not_tupled = false;
3580
3581 let found = match found_trait_ref.args.type_at(1).kind() {
3582 ty::Tuple(tys) => ::alloc::vec::from_elem(ArgKind::empty(), tys.len())vec![ArgKind::empty(); tys.len()],
3583 _ => {
3584 not_tupled = true;
3585 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ArgKind::empty()]))vec![ArgKind::empty()]
3586 }
3587 };
3588
3589 let expected_ty = expected_trait_ref.args.type_at(1);
3590 let expected = match expected_ty.kind() {
3591 ty::Tuple(tys) => {
3592 tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
3593 }
3594 _ => {
3595 not_tupled = true;
3596 ::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())]
3597 }
3598 };
3599
3600 if !self.tcx.is_lang_item(expected_trait_ref.def_id, LangItem::Coroutine) && not_tupled {
3606 return Ok(self.report_and_explain_type_error(
3607 TypeTrace::trait_refs(&obligation.cause, expected_trait_ref, found_trait_ref),
3608 obligation.param_env,
3609 ty::error::TypeError::Mismatch,
3610 ));
3611 }
3612 if found.len() != expected.len() {
3613 let (closure_span, closure_arg_span, found) = found_did
3614 .and_then(|did| {
3615 let node = self.tcx.hir_get_if_local(did)?;
3616 let (found_span, closure_arg_span, found) = self.get_fn_like_arguments(node)?;
3617 Some((Some(found_span), closure_arg_span, found))
3618 })
3619 .unwrap_or((found_span, None, found));
3620
3621 if found.len() != expected.len() {
3627 return Ok(self.report_arg_count_mismatch(
3628 span,
3629 closure_span,
3630 expected,
3631 found,
3632 found_trait_ty.is_closure(),
3633 closure_arg_span,
3634 ));
3635 }
3636 }
3637 Ok(self.report_closure_arg_mismatch(
3638 span,
3639 found_span,
3640 found_trait_ref,
3641 expected_trait_ref,
3642 obligation.cause.code(),
3643 found_node,
3644 obligation.param_env,
3645 ))
3646 }
3647
3648 pub fn get_fn_like_arguments(
3653 &self,
3654 node: Node<'_>,
3655 ) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
3656 let sm = self.tcx.sess.source_map();
3657 Some(match node {
3658 Node::Expr(&hir::Expr {
3659 kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
3660 ..
3661 }) => (
3662 fn_decl_span,
3663 fn_arg_span,
3664 self.tcx
3665 .hir_body(body)
3666 .params
3667 .iter()
3668 .map(|arg| {
3669 if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat
3670 {
3671 Some(ArgKind::Tuple(
3672 Some(span),
3673 args.iter()
3674 .map(|pat| {
3675 sm.span_to_snippet(pat.span)
3676 .ok()
3677 .map(|snippet| (snippet, "_".to_owned()))
3678 })
3679 .collect::<Option<Vec<_>>>()?,
3680 ))
3681 } else {
3682 let name = sm.span_to_snippet(arg.pat.span).ok()?;
3683 Some(ArgKind::Arg(name, "_".to_owned()))
3684 }
3685 })
3686 .collect::<Option<Vec<ArgKind>>>()?,
3687 ),
3688 Node::Item(&hir::Item { kind: hir::ItemKind::Fn { ref sig, .. }, .. })
3689 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
3690 | Node::TraitItem(&hir::TraitItem {
3691 kind: hir::TraitItemKind::Fn(ref sig, _), ..
3692 })
3693 | Node::ForeignItem(&hir::ForeignItem {
3694 kind: hir::ForeignItemKind::Fn(ref sig, _, _),
3695 ..
3696 }) => (
3697 sig.span,
3698 None,
3699 sig.decl
3700 .inputs
3701 .iter()
3702 .map(|arg| match arg.kind {
3703 hir::TyKind::Tup(tys) => ArgKind::Tuple(
3704 Some(arg.span),
3705 ::alloc::vec::from_elem(("_".to_owned(), "_".to_owned()), tys.len())vec![("_".to_owned(), "_".to_owned()); tys.len()],
3706 ),
3707 _ => ArgKind::empty(),
3708 })
3709 .collect::<Vec<ArgKind>>(),
3710 ),
3711 Node::Ctor(variant_data) => {
3712 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| self.tcx.hir_span(id));
3713 (span, None, ::alloc::vec::from_elem(ArgKind::empty(), variant_data.fields().len())vec![ArgKind::empty(); variant_data.fields().len()])
3714 }
3715 _ => {
::core::panicking::panic_fmt(format_args!("non-FnLike node found: {0:?}",
node));
}panic!("non-FnLike node found: {node:?}"),
3716 })
3717 }
3718
3719 pub fn report_arg_count_mismatch(
3723 &self,
3724 span: Span,
3725 found_span: Option<Span>,
3726 expected_args: Vec<ArgKind>,
3727 found_args: Vec<ArgKind>,
3728 is_closure: bool,
3729 closure_arg_span: Option<Span>,
3730 ) -> Diag<'a> {
3731 let kind = if is_closure { "closure" } else { "function" };
3732
3733 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
3734 let arg_length = arguments.len();
3735 let distinct = #[allow(non_exhaustive_omitted_patterns)] match other {
&[ArgKind::Tuple(..)] => true,
_ => false,
}matches!(other, &[ArgKind::Tuple(..)]);
3736 match (arg_length, arguments.get(0)) {
3737 (1, Some(ArgKind::Tuple(_, fields))) => {
3738 ::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())
3739 }
3740 _ => ::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!(
3741 "{} {}argument{}",
3742 arg_length,
3743 if distinct && arg_length > 1 { "distinct " } else { "" },
3744 pluralize!(arg_length)
3745 ),
3746 }
3747 };
3748
3749 let expected_str = args_str(&expected_args, &found_args);
3750 let found_str = args_str(&found_args, &expected_args);
3751
3752 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!(
3753 self.dcx(),
3754 span,
3755 E0593,
3756 "{} is expected to take {}, but it takes {}",
3757 kind,
3758 expected_str,
3759 found_str,
3760 );
3761
3762 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}"));
3763
3764 if let Some(found_span) = found_span {
3765 err.span_label(found_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("takes {0}", found_str))
})format!("takes {found_str}"));
3766
3767 if found_args.is_empty() && is_closure {
3771 let underscores = ::alloc::vec::from_elem("_", expected_args.len())vec!["_"; expected_args.len()].join(", ");
3772 err.span_suggestion_verbose(
3773 closure_arg_span.unwrap_or(found_span),
3774 ::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!(
3775 "consider changing the closure to take and ignore the expected argument{}",
3776 pluralize!(expected_args.len())
3777 ),
3778 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", underscores))
})format!("|{underscores}|"),
3779 Applicability::MachineApplicable,
3780 );
3781 }
3782
3783 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
3784 if fields.len() == expected_args.len() {
3785 let sugg = fields
3786 .iter()
3787 .map(|(name, _)| name.to_owned())
3788 .collect::<Vec<String>>()
3789 .join(", ");
3790 err.span_suggestion_verbose(
3791 found_span,
3792 "change the closure to take multiple arguments instead of a single tuple",
3793 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", sugg))
})format!("|{sugg}|"),
3794 Applicability::MachineApplicable,
3795 );
3796 }
3797 }
3798 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
3799 && fields.len() == found_args.len()
3800 && is_closure
3801 {
3802 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!(
3803 "|({}){}|",
3804 found_args
3805 .iter()
3806 .map(|arg| match arg {
3807 ArgKind::Arg(name, _) => name.to_owned(),
3808 _ => "_".to_owned(),
3809 })
3810 .collect::<Vec<String>>()
3811 .join(", "),
3812 if found_args.iter().any(|arg| match arg {
3814 ArgKind::Arg(_, ty) => ty != "_",
3815 _ => false,
3816 }) {
3817 format!(
3818 ": ({})",
3819 fields
3820 .iter()
3821 .map(|(_, ty)| ty.to_owned())
3822 .collect::<Vec<String>>()
3823 .join(", ")
3824 )
3825 } else {
3826 String::new()
3827 },
3828 );
3829 err.span_suggestion_verbose(
3830 found_span,
3831 "change the closure to accept a tuple instead of individual arguments",
3832 sugg,
3833 Applicability::MachineApplicable,
3834 );
3835 }
3836 }
3837
3838 err
3839 }
3840
3841 pub fn type_implements_fn_trait(
3845 &self,
3846 param_env: ty::ParamEnv<'tcx>,
3847 ty: ty::Binder<'tcx, Ty<'tcx>>,
3848 polarity: ty::PredicatePolarity,
3849 ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
3850 self.commit_if_ok(|_| {
3851 for trait_def_id in [
3852 self.tcx.lang_items().fn_trait(),
3853 self.tcx.lang_items().fn_mut_trait(),
3854 self.tcx.lang_items().fn_once_trait(),
3855 ] {
3856 let Some(trait_def_id) = trait_def_id else { continue };
3857 let var = self.next_ty_var(DUMMY_SP);
3860 let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
3862 let obligation = Obligation::new(
3863 self.tcx,
3864 ObligationCause::dummy(),
3865 param_env,
3866 ty.rebind(ty::TraitPredicate { trait_ref, polarity }),
3867 );
3868 let ocx = ObligationCtxt::new(self);
3869 ocx.register_obligation(obligation);
3870 if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
3871 return Ok((
3872 self.tcx
3873 .fn_trait_kind_from_def_id(trait_def_id)
3874 .expect("expected to map DefId to ClosureKind"),
3875 ty.rebind(self.resolve_vars_if_possible(var)),
3876 ));
3877 }
3878 }
3879
3880 Err(())
3881 })
3882 }
3883
3884 fn report_not_const_evaluatable_error(
3885 &self,
3886 obligation: &PredicateObligation<'tcx>,
3887 span: Span,
3888 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3889 if !self.tcx.features().generic_const_exprs()
3890 && !self.tcx.features().min_generic_const_args()
3891 {
3892 let guar = self
3893 .dcx()
3894 .struct_span_err(span, "constant expression depends on a generic parameter")
3895 .with_note("this may fail depending on what value the parameter takes")
3902 .emit();
3903 return Err(guar);
3904 }
3905
3906 match obligation.predicate.kind().skip_binder() {
3907 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => match ct.kind() {
3908 ty::ConstKind::Alias(_, alias_const) => {
3909 let mut err =
3910 self.dcx().struct_span_err(span, "unconstrained generic constant");
3911
3912 let const_span = alias_const.kind.def_span(self.tcx);
3913 let const_ty = alias_const.type_of(self.tcx).skip_norm_wip();
3914
3915 let msg = "try adding a `where` bound";
3916 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(const_span) {
3917 let code = if const_ty == self.tcx.types.usize {
3918 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); {0}]:", snippet))
})format!("[(); {snippet}]:")
3919 } else if let ty::AliasConstKind::Anon { def_id } = alias_const.kind
3920 && let Some(local_def_id) = def_id.as_local()
3921 && let Some(local_body) = self.tcx.hir_maybe_body_owned_by(local_def_id)
3922 && expr_needs_parens(local_body.value)
3923 {
3924 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); ({0}) as usize]:", snippet))
})format!("[(); ({snippet}) as usize]:")
3925 } else {
3926 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); {0} as usize]:", snippet))
})format!("[(); {snippet} as usize]:")
3927 };
3928
3929 let suggestion_def_id = if let ObligationCauseCode::CompareImplItem {
3930 trait_item_def_id,
3931 ..
3932 } = obligation.cause.code()
3933 {
3934 trait_item_def_id.as_local()
3935 } else {
3936 Some(obligation.cause.body_def_id)
3937 };
3938
3939 if let Some(suggestion_def_id) = suggestion_def_id
3940 && let Some(generics) = self.tcx.hir_get_generics(suggestion_def_id)
3941 {
3942 err.span_suggestion_verbose(
3943 generics.tail_span_for_predicate_suggestion(),
3944 msg,
3945 ::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()),
3946 Applicability::MaybeIncorrect,
3947 );
3948 } else {
3949 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: where {1}", msg, code))
})format!("{msg}: where {code}"));
3950 };
3951 } else {
3952 err.help(msg);
3953 }
3954 Ok(err)
3955 }
3956 ty::ConstKind::Expr(_) => {
3957 let err = self
3958 .dcx()
3959 .struct_span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unconstrained generic constant `{0}`",
ct))
})format!("unconstrained generic constant `{ct}`"));
3960 Ok(err)
3961 }
3962 _ => {
3963 ::rustc_middle::util::bug::bug_fmt(format_args!("const evaluatable failed for non-alias const `{0:?}`",
ct));bug!("const evaluatable failed for non-alias const `{ct:?}`");
3964 }
3965 },
3966 _ => {
3967 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpected non-ConstEvaluatable predicate, this should not be reachable"))span_bug!(
3968 span,
3969 "unexpected non-ConstEvaluatable predicate, this should not be reachable"
3970 )
3971 }
3972 }
3973 }
3974}