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