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