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, PrintTraitPredicateExt as _, PrintTraitRefExt as _,
29 with_forced_trimmed_paths,
30};
31use rustc_middle::ty::{
32 self, GenericArgKind, TraitRef, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
33 TypeVisitableExt, 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 }
890 diag
891 }
892
893 fn emit_specialized_closure_kind_error(
894 &self,
895 obligation: &PredicateObligation<'tcx>,
896 mut trait_pred: ty::PolyTraitPredicate<'tcx>,
897 ) -> Option<ErrorGuaranteed> {
898 if self.tcx.is_lang_item(trait_pred.def_id(), LangItem::AsyncFnKindHelper) {
901 let mut code = obligation.cause.code();
902 if let ObligationCauseCode::FunctionArg { parent_code, .. } = code {
904 code = &**parent_code;
905 }
906 if let Some((_, Some(parent))) = code.parent_with_predicate() {
908 trait_pred = parent;
909 }
910 }
911
912 let self_ty = trait_pred.self_ty().skip_binder();
913
914 let (expected_kind, trait_prefix) =
915 if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) {
916 (expected_kind, "")
917 } else if let Some(expected_kind) =
918 self.tcx.async_fn_trait_kind_from_def_id(trait_pred.def_id())
919 {
920 (expected_kind, "Async")
921 } else {
922 return None;
923 };
924
925 let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() {
926 ty::Closure(def_id, args) => {
927 (def_id, args.as_closure().sig().map_bound(|sig| sig.inputs()[0]), false)
928 }
929 ty::CoroutineClosure(def_id, args) => (
930 def_id,
931 args.as_coroutine_closure()
932 .coroutine_closure_sig()
933 .map_bound(|sig| sig.tupled_inputs_ty),
934 !args.as_coroutine_closure().tupled_upvars_ty().is_ty_var()
935 && args.as_coroutine_closure().has_self_borrows(),
936 ),
937 _ => return None,
938 };
939
940 let expected_args = trait_pred.map_bound(|trait_pred| trait_pred.trait_ref.args.type_at(1));
941
942 if self.enter_forall(found_args, |found_args| {
945 self.enter_forall(expected_args, |expected_args| {
946 !self.can_eq(obligation.param_env, expected_args, found_args)
947 })
948 }) {
949 return None;
950 }
951
952 if let Some(found_kind) = self.closure_kind(self_ty)
953 && !found_kind.extends(expected_kind)
954 {
955 let mut err = self.report_closure_error(
956 &obligation,
957 closure_def_id,
958 found_kind,
959 expected_kind,
960 trait_prefix,
961 );
962 self.note_obligation_cause(&mut err, &obligation);
963 return Some(err.emit());
964 }
965
966 if has_self_borrows && expected_kind != ty::ClosureKind::FnOnce {
970 let coro_kind = match self
971 .tcx
972 .coroutine_kind(self.tcx.coroutine_for_closure(closure_def_id))
973 .unwrap()
974 {
975 rustc_hir::CoroutineKind::Desugared(desugaring, _) => desugaring.to_string(),
976 coro => coro.to_string(),
977 };
978 let mut err = self.dcx().create_err(CoroClosureNotFn {
979 span: self.tcx.def_span(closure_def_id),
980 kind: expected_kind.as_str(),
981 coro_kind,
982 });
983 self.note_obligation_cause(&mut err, &obligation);
984 return Some(err.emit());
985 }
986
987 None
988 }
989
990 fn fn_arg_obligation(
991 &self,
992 obligation: &PredicateObligation<'tcx>,
993 ) -> Result<(), ErrorGuaranteed> {
994 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
995 && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
996 && let arg = arg.peel_borrows()
997 && let hir::ExprKind::Path(hir::QPath::Resolved(
998 None,
999 hir::Path { res: hir::def::Res::Local(hir_id), .. },
1000 )) = arg.kind
1001 && let Node::Pat(pat) = self.tcx.hir_node(*hir_id)
1002 && let Some((preds, guar)) = self.reported_trait_errors.borrow().get(&pat.span)
1003 && preds.contains(&obligation.as_goal())
1004 {
1005 return Err(*guar);
1006 }
1007 Ok(())
1008 }
1009
1010 fn detect_negative_literal(
1011 &self,
1012 obligation: &PredicateObligation<'tcx>,
1013 trait_pred: ty::PolyTraitPredicate<'tcx>,
1014 err: &mut Diag<'_>,
1015 ) -> bool {
1016 if let ObligationCauseCode::UnOp { hir_id, .. } = obligation.cause.code()
1017 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1018 && let hir::ExprKind::Unary(hir::UnOp::Neg, inner) = expr.kind
1019 && let hir::ExprKind::Lit(lit) = inner.kind
1020 && let LitKind::Int(_, LitIntType::Unsuffixed) = lit.node
1021 {
1022 err.span_suggestion_verbose(
1023 lit.span.shrink_to_hi(),
1024 "consider specifying an integer type that can be negative",
1025 match trait_pred.skip_binder().self_ty().kind() {
1026 ty::Uint(ty::UintTy::Usize) => "isize",
1027 ty::Uint(ty::UintTy::U8) => "i8",
1028 ty::Uint(ty::UintTy::U16) => "i16",
1029 ty::Uint(ty::UintTy::U32) => "i32",
1030 ty::Uint(ty::UintTy::U64) => "i64",
1031 ty::Uint(ty::UintTy::U128) => "i128",
1032 _ => "i64",
1033 }
1034 .to_string(),
1035 Applicability::MaybeIncorrect,
1036 );
1037 return true;
1038 }
1039 false
1040 }
1041
1042 fn try_conversion_context(
1046 &self,
1047 obligation: &PredicateObligation<'tcx>,
1048 trait_pred: ty::PolyTraitPredicate<'tcx>,
1049 err: &mut Diag<'_>,
1050 ) -> (bool, bool) {
1051 let span = obligation.cause.span;
1052 struct FindMethodSubexprOfTry {
1054 search_span: Span,
1055 }
1056 impl<'v> Visitor<'v> for FindMethodSubexprOfTry {
1057 type Result = ControlFlow<&'v hir::Expr<'v>>;
1058 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
1059 if let hir::ExprKind::Match(expr, _arms, hir::MatchSource::TryDesugar(_)) = ex.kind
1060 && ex.span.with_lo(ex.span.hi() - BytePos(1)).source_equal(self.search_span)
1061 && let hir::ExprKind::Call(_, [expr, ..]) = expr.kind
1062 {
1063 ControlFlow::Break(expr)
1064 } else {
1065 hir::intravisit::walk_expr(self, ex)
1066 }
1067 }
1068 }
1069 let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_id);
1070 let Some(body_id) = self.tcx.hir_node(hir_id).body_id() else { return (false, false) };
1071 let ControlFlow::Break(expr) =
1072 (FindMethodSubexprOfTry { search_span: span }).visit_body(self.tcx.hir_body(body_id))
1073 else {
1074 return (false, false);
1075 };
1076 let Some(typeck) = &self.typeck_results else {
1077 return (false, false);
1078 };
1079 let ObligationCauseCode::QuestionMark = obligation.cause.code().peel_derives() else {
1080 return (false, false);
1081 };
1082 let self_ty = trait_pred.skip_binder().self_ty();
1083 let found_ty = trait_pred.skip_binder().trait_ref.args.get(1).and_then(|a| a.as_type());
1084 let noted_missing_impl =
1085 self.note_missing_impl_for_question_mark(err, self_ty, found_ty, trait_pred);
1086
1087 let mut prev_ty = self.resolve_vars_if_possible(
1088 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1089 );
1090
1091 let get_e_type = |prev_ty: Ty<'tcx>| -> Option<Ty<'tcx>> {
1095 let ty::Adt(def, args) = prev_ty.kind() else {
1096 return None;
1097 };
1098 let Some(arg) = args.get(1) else {
1099 return None;
1100 };
1101 if !self.tcx.is_diagnostic_item(sym::Result, def.did()) {
1102 return None;
1103 }
1104 arg.as_type()
1105 };
1106
1107 let mut suggested = false;
1108 let mut chain = ::alloc::vec::Vec::new()vec![];
1109
1110 let mut expr = expr;
1112 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
1113 expr = rcvr_expr;
1117 chain.push((span, prev_ty));
1118
1119 let next_ty = self.resolve_vars_if_possible(
1120 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1121 );
1122
1123 let is_diagnostic_item = |symbol: Symbol, ty: Ty<'tcx>| {
1124 let ty::Adt(def, _) = ty.kind() else {
1125 return false;
1126 };
1127 self.tcx.is_diagnostic_item(symbol, def.did())
1128 };
1129 if let Some(ty) = get_e_type(prev_ty)
1133 && let Some(found_ty) = found_ty
1134 && (
1139 ( path_segment.ident.name == sym::map_err
1141 && is_diagnostic_item(sym::Result, next_ty)
1142 ) || ( path_segment.ident.name == sym::ok_or_else
1144 && is_diagnostic_item(sym::Option, next_ty)
1145 )
1146 )
1147 && let ty::Tuple(tys) = found_ty.kind()
1149 && tys.is_empty()
1150 && self.can_eq(obligation.param_env, ty, found_ty)
1152 && let [arg] = args
1154 && let hir::ExprKind::Closure(closure) = arg.kind
1155 && let body = self.tcx.hir_body(closure.body)
1157 && let hir::ExprKind::Block(block, _) = body.value.kind
1158 && let None = block.expr
1159 && let [.., stmt] = block.stmts
1161 && let hir::StmtKind::Semi(expr) = stmt.kind
1162 && let expr_ty = self.resolve_vars_if_possible(
1163 typeck.expr_ty_adjusted_opt(expr)
1164 .unwrap_or(Ty::new_misc_error(self.tcx)),
1165 )
1166 && self
1167 .infcx
1168 .type_implements_trait(
1169 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1170 [self_ty, expr_ty],
1171 obligation.param_env,
1172 )
1173 .must_apply_modulo_regions()
1174 {
1175 suggested = true;
1176 err.span_suggestion_short(
1177 stmt.span.with_lo(expr.span.hi()),
1178 "remove this semicolon",
1179 String::new(),
1180 Applicability::MachineApplicable,
1181 );
1182 }
1183
1184 prev_ty = next_ty;
1185
1186 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1187 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
1188 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
1189 {
1190 let parent = self.tcx.parent_hir_node(binding.hir_id);
1191 if let hir::Node::LetStmt(local) = parent
1193 && let Some(binding_expr) = local.init
1194 {
1195 expr = binding_expr;
1197 }
1198 if let hir::Node::Param(_param) = parent {
1199 break;
1201 }
1202 }
1203 }
1204 prev_ty = self.resolve_vars_if_possible(
1208 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1209 );
1210 chain.push((expr.span, prev_ty));
1211
1212 let mut prev = None;
1213 let mut iter = chain.into_iter().rev().peekable();
1214 while let Some((span, err_ty)) = iter.next() {
1215 let is_last = iter.peek().is_none();
1216 let err_ty = get_e_type(err_ty);
1217 let err_ty = match (err_ty, prev) {
1218 (Some(err_ty), Some(prev)) if !self.can_eq(obligation.param_env, err_ty, prev) => {
1219 err_ty
1220 }
1221 (Some(err_ty), None) => err_ty,
1222 _ => {
1223 prev = err_ty;
1224 continue;
1225 }
1226 };
1227
1228 let implements_from = self
1229 .infcx
1230 .type_implements_trait(
1231 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1232 [self_ty, err_ty],
1233 obligation.param_env,
1234 )
1235 .must_apply_modulo_regions();
1236
1237 let err_ty_str = self.tcx.short_string(err_ty, err.long_ty_path());
1238 let label = if !implements_from && is_last {
1239 ::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!(
1240 "this can't be annotated with `?` because it has type `Result<_, {err_ty_str}>`"
1241 )
1242 } else {
1243 ::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}>`")
1244 };
1245
1246 if !suggested || !implements_from {
1247 err.span_label(span, label);
1248 }
1249 prev = Some(err_ty);
1250 }
1251 (suggested, noted_missing_impl)
1252 }
1253
1254 fn note_missing_impl_for_question_mark(
1255 &self,
1256 err: &mut Diag<'_>,
1257 self_ty: Ty<'_>,
1258 found_ty: Option<Ty<'_>>,
1259 trait_pred: ty::PolyTraitPredicate<'tcx>,
1260 ) -> bool {
1261 match (self_ty.kind(), found_ty) {
1262 (ty::Adt(def, _), Some(ty))
1263 if let ty::Adt(found, _) = ty.kind()
1264 && def.did().is_local()
1265 && found.did().is_local() =>
1266 {
1267 err.span_note(
1268 self.tcx.def_span(def.did()),
1269 ::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}>`"),
1270 );
1271 }
1272 (ty::Adt(def, _), None) if def.did().is_local() => {
1273 let trait_path = self.tcx.short_string(
1274 trait_pred.skip_binder().trait_ref.print_only_trait_path(),
1275 err.long_ty_path(),
1276 );
1277 err.span_note(
1278 self.tcx.def_span(def.did()),
1279 ::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}`"),
1280 );
1281 }
1282 (ty::Adt(def, _), Some(ty)) if def.did().is_local() => {
1283 err.span_note(
1284 self.tcx.def_span(def.did()),
1285 ::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}>`"),
1286 );
1287 }
1288 (_, Some(ty))
1289 if let ty::Adt(def, _) = ty.kind()
1290 && def.did().is_local() =>
1291 {
1292 err.span_note(
1293 self.tcx.def_span(def.did()),
1294 ::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}>`"),
1295 );
1296 }
1297 _ => return false,
1298 }
1299 true
1300 }
1301
1302 fn report_const_param_not_wf(
1303 &self,
1304 ty: Ty<'tcx>,
1305 obligation: &PredicateObligation<'tcx>,
1306 ) -> Diag<'a> {
1307 let def_id = obligation.cause.body_id;
1308 let span = self.tcx.ty_span(def_id);
1309
1310 let mut file = None;
1311 let ty_str = self.tcx.short_string(ty, &mut file);
1312 let mut diag = match ty.kind() {
1313 ty::Float(_) => {
1314 {
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!(
1315 self.dcx(),
1316 span,
1317 E0741,
1318 "`{ty_str}` is forbidden as the type of a const generic parameter",
1319 )
1320 }
1321 ty::FnPtr(..) => {
1322 {
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!(
1323 self.dcx(),
1324 span,
1325 E0741,
1326 "using function pointers as const generic parameters is forbidden",
1327 )
1328 }
1329 ty::RawPtr(_, _) => {
1330 {
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!(
1331 self.dcx(),
1332 span,
1333 E0741,
1334 "using raw pointers as const generic parameters is forbidden",
1335 )
1336 }
1337 ty::Adt(def, _) => {
1338 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!(
1340 self.dcx(),
1341 span,
1342 E0741,
1343 "`{ty_str}` must implement `ConstParamTy` to be used as the type of a const generic parameter",
1344 );
1345 if let Some(span) = self.tcx.hir_span_if_local(def.did())
1348 && obligation.cause.code().parent().is_none()
1349 {
1350 if ty.is_structural_eq_shallow(self.tcx) {
1351 diag.span_suggestion(
1352 span.shrink_to_lo(),
1353 ::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()),
1354 "#[derive(ConstParamTy)]\n",
1355 Applicability::MachineApplicable,
1356 );
1357 } else {
1358 diag.span_suggestion(
1361 span.shrink_to_lo(),
1362 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {0}",
def.descr()))
})format!(
1363 "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {}",
1364 def.descr()
1365 ),
1366 "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1367 Applicability::MachineApplicable,
1368 );
1369 }
1370 }
1371 diag
1372 }
1373 _ => {
1374 {
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!(
1375 self.dcx(),
1376 span,
1377 E0741,
1378 "`{ty_str}` can't be used as a const parameter type",
1379 )
1380 }
1381 };
1382 diag.long_ty_path = file;
1383
1384 let mut code = obligation.cause.code();
1385 let mut pred = obligation.predicate.as_trait_clause();
1386 while let Some((next_code, next_pred)) = code.parent_with_predicate() {
1387 if let Some(pred) = pred {
1388 self.enter_forall(pred, |pred| {
1389 let ty = self.tcx.short_string(pred.self_ty(), diag.long_ty_path());
1390 let trait_path = self
1391 .tcx
1392 .short_string(pred.print_modifiers_and_trait_path(), diag.long_ty_path());
1393 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"));
1394 })
1395 }
1396 code = next_code;
1397 pred = next_pred;
1398 }
1399
1400 diag
1401 }
1402}
1403
1404impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
1405 fn can_match_trait(
1406 &self,
1407 param_env: ty::ParamEnv<'tcx>,
1408 goal: ty::TraitPredicate<'tcx>,
1409 assumption: ty::PolyTraitPredicate<'tcx>,
1410 ) -> bool {
1411 if goal.polarity != assumption.polarity() {
1413 return false;
1414 }
1415
1416 let trait_assumption = self.instantiate_binder_with_fresh_vars(
1417 DUMMY_SP,
1418 infer::BoundRegionConversionTime::HigherRankedType,
1419 assumption,
1420 );
1421
1422 self.can_eq(param_env, goal.trait_ref, trait_assumption.trait_ref)
1423 }
1424
1425 fn can_match_host_effect(
1426 &self,
1427 param_env: ty::ParamEnv<'tcx>,
1428 goal: ty::HostEffectPredicate<'tcx>,
1429 assumption: ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>,
1430 ) -> bool {
1431 let assumption = self.instantiate_binder_with_fresh_vars(
1432 DUMMY_SP,
1433 infer::BoundRegionConversionTime::HigherRankedType,
1434 assumption,
1435 );
1436
1437 assumption.constness.satisfies(goal.constness)
1438 && self.can_eq(param_env, goal.trait_ref, assumption.trait_ref)
1439 }
1440
1441 fn as_host_effect_clause(
1442 predicate: ty::Predicate<'tcx>,
1443 ) -> Option<ty::Binder<'tcx, ty::HostEffectPredicate<'tcx>>> {
1444 predicate.as_clause().and_then(|clause| match clause.kind().skip_binder() {
1445 ty::ClauseKind::HostEffect(pred) => Some(clause.kind().rebind(pred)),
1446 _ => None,
1447 })
1448 }
1449
1450 fn can_match_projection(
1451 &self,
1452 param_env: ty::ParamEnv<'tcx>,
1453 goal: ty::ProjectionPredicate<'tcx>,
1454 assumption: ty::PolyProjectionPredicate<'tcx>,
1455 ) -> bool {
1456 let assumption = self.instantiate_binder_with_fresh_vars(
1457 DUMMY_SP,
1458 infer::BoundRegionConversionTime::HigherRankedType,
1459 assumption,
1460 );
1461
1462 self.can_eq(param_env, goal.projection_term, assumption.projection_term)
1463 && self.can_eq(param_env, goal.term, assumption.term)
1464 }
1465
1466 x;#[instrument(level = "debug", skip(self), ret)]
1469 pub(super) fn error_implies(
1470 &self,
1471 cond: Goal<'tcx, ty::Predicate<'tcx>>,
1472 error: Goal<'tcx, ty::Predicate<'tcx>>,
1473 ) -> bool {
1474 if cond == error {
1475 return true;
1476 }
1477
1478 if cond.param_env != error.param_env {
1482 return false;
1483 }
1484 let param_env = error.param_env;
1485
1486 if let Some(error) = error.predicate.as_trait_clause() {
1487 self.enter_forall(error, |error| {
1488 elaborate(self.tcx, std::iter::once(cond.predicate))
1489 .filter_map(|implied| implied.as_trait_clause())
1490 .any(|implied| self.can_match_trait(param_env, error, implied))
1491 })
1492 } else if let Some(error) = Self::as_host_effect_clause(error.predicate) {
1493 self.enter_forall(error, |error| {
1494 elaborate(self.tcx, std::iter::once(cond.predicate))
1495 .filter_map(Self::as_host_effect_clause)
1496 .any(|implied| self.can_match_host_effect(param_env, error, implied))
1497 })
1498 } else if let Some(error) = error.predicate.as_projection_clause() {
1499 self.enter_forall(error, |error| {
1500 elaborate(self.tcx, std::iter::once(cond.predicate))
1501 .filter_map(|implied| implied.as_projection_clause())
1502 .any(|implied| self.can_match_projection(param_env, error, implied))
1503 })
1504 } else {
1505 false
1506 }
1507 }
1508
1509 #[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(1509u32),
::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 Ok(normalized_term) =
ocx.structurally_normalize_term(&ObligationCause::dummy(),
obligation.param_env,
Unnormalized::new_wip(alias_term.to_term(self.tcx))) else {
return None;
};
if let Err(terr) =
ocx.eq(&ObligationCause::dummy(), obligation.param_env,
expected_term, normalized_term) {
Some((terr, self.resolve_vars_if_possible(normalized_term)))
} else { None }
};
if let Some(lhs) = lhs.to_alias_term(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)]
1510 pub(super) fn report_projection_error(
1511 &self,
1512 obligation: &PredicateObligation<'tcx>,
1513 error: &MismatchedProjectionTypes<'tcx>,
1514 ) -> ErrorGuaranteed {
1515 let predicate = self.resolve_vars_if_possible(obligation.predicate);
1516
1517 if let Err(e) = predicate.error_reported() {
1518 return e;
1519 }
1520
1521 self.probe(|_| {
1522 let bound_predicate = predicate.kind();
1527 let (values, err) = match bound_predicate.skip_binder() {
1528 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
1529 let ocx = ObligationCtxt::new(self);
1530
1531 let data = self.instantiate_binder_with_fresh_vars(
1532 obligation.cause.span,
1533 infer::BoundRegionConversionTime::HigherRankedType,
1534 bound_predicate.rebind(data),
1535 );
1536 let unnormalized_term = data.projection_term.to_term(self.tcx);
1537 let normalized_term = ocx.normalize(
1540 &obligation.cause,
1541 obligation.param_env,
1542 Unnormalized::new_wip(unnormalized_term),
1543 );
1544
1545 let _ = ocx.try_evaluate_obligations();
1551
1552 if let Err(new_err) =
1553 ocx.eq(&obligation.cause, obligation.param_env, data.term, normalized_term)
1554 {
1555 (
1556 Some((
1557 data.projection_term,
1558 self.resolve_vars_if_possible(normalized_term),
1559 data.term,
1560 )),
1561 new_err,
1562 )
1563 } else {
1564 (None, error.err)
1565 }
1566 }
1567 ty::PredicateKind::AliasRelate(lhs, rhs, _) => {
1568 let derive_better_type_error =
1569 |alias_term: ty::AliasTerm<'tcx>, expected_term: ty::Term<'tcx>| {
1570 let ocx = ObligationCtxt::new(self);
1571
1572 let Ok(normalized_term) = ocx.structurally_normalize_term(
1573 &ObligationCause::dummy(),
1574 obligation.param_env,
1575 Unnormalized::new_wip(alias_term.to_term(self.tcx)),
1576 ) else {
1577 return None;
1578 };
1579
1580 if let Err(terr) = ocx.eq(
1581 &ObligationCause::dummy(),
1582 obligation.param_env,
1583 expected_term,
1584 normalized_term,
1585 ) {
1586 Some((terr, self.resolve_vars_if_possible(normalized_term)))
1587 } else {
1588 None
1589 }
1590 };
1591
1592 if let Some(lhs) = lhs.to_alias_term(self.tcx)
1593 && let ty::AliasTermKind::ProjectionTy { .. }
1594 | ty::AliasTermKind::ProjectionConst { .. } = lhs.kind(self.tcx)
1595 && let Some((better_type_err, expected_term)) =
1596 derive_better_type_error(lhs, rhs)
1597 {
1598 (
1599 Some((lhs, self.resolve_vars_if_possible(expected_term), rhs)),
1600 better_type_err,
1601 )
1602 } else if let Some(rhs) = rhs.to_alias_term(self.tcx)
1603 && let ty::AliasTermKind::ProjectionTy { .. }
1604 | ty::AliasTermKind::ProjectionConst { .. } = rhs.kind(self.tcx)
1605 && let Some((better_type_err, expected_term)) =
1606 derive_better_type_error(rhs, lhs)
1607 {
1608 (
1609 Some((rhs, self.resolve_vars_if_possible(expected_term), lhs)),
1610 better_type_err,
1611 )
1612 } else {
1613 (None, error.err)
1614 }
1615 }
1616 _ => (None, error.err),
1617 };
1618
1619 let mut file = None;
1620 let (msg, span, closure_span) = values
1621 .and_then(|(predicate, normalized_term, expected_term)| {
1622 self.maybe_detailed_projection_msg(
1623 obligation.cause.span,
1624 predicate,
1625 normalized_term,
1626 expected_term,
1627 &mut file,
1628 )
1629 })
1630 .unwrap_or_else(|| {
1631 (
1632 with_forced_trimmed_paths!(format!(
1633 "type mismatch resolving `{}`",
1634 self.tcx
1635 .short_string(self.resolve_vars_if_possible(predicate), &mut file),
1636 )),
1637 obligation.cause.span,
1638 None,
1639 )
1640 });
1641 let mut diag = struct_span_code_err!(self.dcx(), span, E0271, "{msg}");
1642 *diag.long_ty_path() = file;
1643 if let Some(span) = closure_span {
1644 diag.span_label(span, "this closure");
1661 if !span.overlaps(obligation.cause.span) {
1662 diag.span_label(obligation.cause.span, "closure used here");
1664 }
1665 }
1666
1667 let secondary_span = self.probe(|_| {
1668 let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1669 predicate.kind().skip_binder()
1670 else {
1671 return None;
1672 };
1673
1674 let trait_ref = self.enter_forall_and_leak_universe(
1675 predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)),
1676 );
1677 let Ok(Some(ImplSource::UserDefined(impl_data))) =
1678 SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref))
1679 else {
1680 return None;
1681 };
1682
1683 let Ok(node) =
1684 specialization_graph::assoc_def(self.tcx, impl_data.impl_def_id, proj.def_id())
1685 else {
1686 return None;
1687 };
1688
1689 if !node.is_final() {
1690 return None;
1691 }
1692
1693 match self.tcx.hir_get_if_local(node.item.def_id) {
1694 Some(
1695 hir::Node::TraitItem(hir::TraitItem {
1696 kind: hir::TraitItemKind::Type(_, Some(ty)),
1697 ..
1698 })
1699 | hir::Node::ImplItem(hir::ImplItem {
1700 kind: hir::ImplItemKind::Type(ty),
1701 ..
1702 }),
1703 ) => Some((
1704 ty.span,
1705 with_forced_trimmed_paths!(Cow::from(format!(
1706 "type mismatch resolving `{}`",
1707 self.tcx.short_string(
1708 self.resolve_vars_if_possible(predicate),
1709 diag.long_ty_path()
1710 ),
1711 ))),
1712 true,
1713 )),
1714 _ => None,
1715 }
1716 });
1717
1718 self.note_type_err(
1719 &mut diag,
1720 &obligation.cause,
1721 secondary_span,
1722 values.map(|(_, normalized_ty, expected_ty)| {
1723 obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(
1724 expected_ty,
1725 normalized_ty,
1726 )))
1727 }),
1728 err,
1729 false,
1730 Some(span),
1731 );
1732 self.note_obligation_cause(&mut diag, obligation);
1733 diag.emit()
1734 })
1735 }
1736
1737 fn maybe_detailed_projection_msg(
1738 &self,
1739 mut span: Span,
1740 projection_term: ty::AliasTerm<'tcx>,
1741 normalized_ty: ty::Term<'tcx>,
1742 expected_ty: ty::Term<'tcx>,
1743 long_ty_path: &mut Option<PathBuf>,
1744 ) -> Option<(String, Span, Option<Span>)> {
1745 let trait_def_id = projection_term.trait_def_id(self.tcx);
1746 let self_ty = projection_term.self_ty();
1747
1748 {
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! {
1749 if self.tcx.is_lang_item(projection_term.def_id(), LangItem::FnOnceOutput) {
1750 let (span, closure_span) = if let ty::Closure(def_id, _) = *self_ty.kind() {
1751 let def_span = self.tcx.def_span(def_id);
1752 if let Some(local_def_id) = def_id.as_local()
1753 && let node = self.tcx.hir_node_by_def_id(local_def_id)
1754 && let Some(fn_decl) = node.fn_decl()
1755 && let Some(id) = node.body_id()
1756 {
1757 span = match fn_decl.output {
1758 hir::FnRetTy::Return(ty) => ty.span,
1759 hir::FnRetTy::DefaultReturn(_) => {
1760 let body = self.tcx.hir_body(id);
1761 match body.value.kind {
1762 hir::ExprKind::Block(
1763 hir::Block { expr: Some(expr), .. },
1764 _,
1765 ) => expr.span,
1766 hir::ExprKind::Block(
1767 hir::Block {
1768 expr: None, stmts: [.., last], ..
1769 },
1770 _,
1771 ) => last.span,
1772 _ => body.value.span,
1773 }
1774 }
1775 };
1776 }
1777 (span, Some(def_span))
1778 } else {
1779 (span, None)
1780 };
1781 let item = match self_ty.kind() {
1782 ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
1783 _ => self.tcx.short_string(self_ty, long_ty_path),
1784 };
1785 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1786 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1787 Some((format!(
1788 "expected `{item}` to return `{expected_ty}`, but it returns `{normalized_ty}`",
1789 ), span, closure_span))
1790 } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
1791 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
1792 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
1793 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
1794 Some((format!(
1795 "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
1796 resolves to `{normalized_ty}`"
1797 ), span, None))
1798 } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
1799 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
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 `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
1804 yields `{normalized_ty}`"
1805 ), span, None))
1806 } else {
1807 None
1808 }
1809 }
1810 }
1811
1812 pub fn fuzzy_match_tys(
1813 &self,
1814 mut a: Ty<'tcx>,
1815 mut b: Ty<'tcx>,
1816 ignoring_lifetimes: bool,
1817 ) -> Option<CandidateSimilarity> {
1818 fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
1821 match t.kind() {
1822 ty::Bool => Some(0),
1823 ty::Char => Some(1),
1824 ty::Str => Some(2),
1825 ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => Some(2),
1826 ty::Int(..)
1827 | ty::Uint(..)
1828 | ty::Float(..)
1829 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
1830 ty::Ref(..) | ty::RawPtr(..) => Some(5),
1831 ty::Array(..) | ty::Slice(..) => Some(6),
1832 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
1833 ty::Dynamic(..) => Some(8),
1834 ty::Closure(..) => Some(9),
1835 ty::Tuple(..) => Some(10),
1836 ty::Param(..) => Some(11),
1837 ty::Alias(ty::AliasTy { kind: ty::Projection { .. }, .. }) => Some(12),
1838 ty::Alias(ty::AliasTy { kind: ty::Inherent { .. }, .. }) => Some(13),
1839 ty::Alias(ty::AliasTy { kind: ty::Opaque { .. }, .. }) => Some(14),
1840 ty::Alias(ty::AliasTy { kind: ty::Free { .. }, .. }) => Some(15),
1841 ty::Never => Some(16),
1842 ty::Adt(..) => Some(17),
1843 ty::Coroutine(..) => Some(18),
1844 ty::Foreign(..) => Some(19),
1845 ty::CoroutineWitness(..) => Some(20),
1846 ty::CoroutineClosure(..) => Some(21),
1847 ty::Pat(..) => Some(22),
1848 ty::UnsafeBinder(..) => Some(23),
1849 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
1850 }
1851 }
1852
1853 let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
1854 loop {
1855 match t.kind() {
1856 ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => t = *inner,
1857 _ => break t,
1858 }
1859 }
1860 };
1861
1862 if !ignoring_lifetimes {
1863 a = strip_references(a);
1864 b = strip_references(b);
1865 }
1866
1867 let cat_a = type_category(self.tcx, a)?;
1868 let cat_b = type_category(self.tcx, b)?;
1869 if a == b {
1870 Some(CandidateSimilarity::Exact { ignoring_lifetimes })
1871 } else if cat_a == cat_b {
1872 match (a.kind(), b.kind()) {
1873 (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
1874 (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
1875 (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
1881 self.fuzzy_match_tys(a, b, true).is_some()
1882 }
1883 _ => true,
1884 }
1885 .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
1886 } else if ignoring_lifetimes {
1887 None
1888 } else {
1889 self.fuzzy_match_tys(a, b, true)
1890 }
1891 }
1892
1893 pub(super) fn describe_closure(&self, kind: hir::ClosureKind) -> &'static str {
1894 match kind {
1895 hir::ClosureKind::Closure => "a closure",
1896 hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => "a coroutine",
1897 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1898 hir::CoroutineDesugaring::Async,
1899 hir::CoroutineSource::Block,
1900 )) => "an async block",
1901 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1902 hir::CoroutineDesugaring::Async,
1903 hir::CoroutineSource::Fn,
1904 )) => "an async function",
1905 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1906 hir::CoroutineDesugaring::Async,
1907 hir::CoroutineSource::Closure,
1908 ))
1909 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
1910 "an async closure"
1911 }
1912 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1913 hir::CoroutineDesugaring::AsyncGen,
1914 hir::CoroutineSource::Block,
1915 )) => "an async gen block",
1916 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1917 hir::CoroutineDesugaring::AsyncGen,
1918 hir::CoroutineSource::Fn,
1919 )) => "an async gen function",
1920 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1921 hir::CoroutineDesugaring::AsyncGen,
1922 hir::CoroutineSource::Closure,
1923 ))
1924 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
1925 "an async gen closure"
1926 }
1927 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1928 hir::CoroutineDesugaring::Gen,
1929 hir::CoroutineSource::Block,
1930 )) => "a gen block",
1931 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1932 hir::CoroutineDesugaring::Gen,
1933 hir::CoroutineSource::Fn,
1934 )) => "a gen function",
1935 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
1936 hir::CoroutineDesugaring::Gen,
1937 hir::CoroutineSource::Closure,
1938 ))
1939 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => "a gen closure",
1940 }
1941 }
1942
1943 pub(super) fn find_similar_impl_candidates(
1944 &self,
1945 trait_pred: ty::PolyTraitPredicate<'tcx>,
1946 ) -> Vec<ImplCandidate<'tcx>> {
1947 let mut candidates: Vec<_> = self
1948 .tcx
1949 .all_impls(trait_pred.def_id())
1950 .filter_map(|def_id| {
1951 let imp = self.tcx.impl_trait_header(def_id);
1952 if imp.polarity != ty::ImplPolarity::Positive
1953 || !self.tcx.is_user_visible_dep(def_id.krate)
1954 {
1955 return None;
1956 }
1957 let imp = imp.trait_ref.skip_binder();
1958
1959 self.fuzzy_match_tys(trait_pred.skip_binder().self_ty(), imp.self_ty(), false).map(
1960 |similarity| ImplCandidate { trait_ref: imp, similarity, impl_def_id: def_id },
1961 )
1962 })
1963 .collect();
1964 if candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
1965 candidates.retain(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. }));
1969 }
1970 candidates
1971 }
1972
1973 pub(super) fn report_similar_impl_candidates(
1974 &self,
1975 impl_candidates: &[ImplCandidate<'tcx>],
1976 obligation: &PredicateObligation<'tcx>,
1977 trait_pred: ty::PolyTraitPredicate<'tcx>,
1978 body_def_id: LocalDefId,
1979 err: &mut Diag<'_>,
1980 other: bool,
1981 param_env: ty::ParamEnv<'tcx>,
1982 ) -> bool {
1983 let parent_map = self.tcx.visible_parent_map(());
1984 let alternative_candidates = |def_id: DefId| {
1985 let mut impl_candidates: Vec<_> = self
1986 .tcx
1987 .all_impls(def_id)
1988 .filter(|def_id| !self.tcx.do_not_recommend_impl(*def_id))
1990 .map(|def_id| (self.tcx.impl_trait_header(def_id), def_id))
1992 .filter_map(|(header, def_id)| {
1993 (header.polarity == ty::ImplPolarity::Positive
1994 || self.tcx.is_automatically_derived(def_id))
1995 .then(|| (header.trait_ref.instantiate_identity().skip_norm_wip(), def_id))
1996 })
1997 .filter(|(trait_ref, _)| {
1998 let self_ty = trait_ref.self_ty();
1999 if let ty::Param(_) = self_ty.kind() {
2001 false
2002 }
2003 else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
2005 let mut did = def.did();
2009 if self.tcx.visibility(did).is_accessible_from(body_def_id, self.tcx) {
2010 if !did.is_local() {
2012 let mut previously_seen_dids: FxHashSet<DefId> = Default::default();
2013 previously_seen_dids.insert(did);
2014 while let Some(&parent) = parent_map.get(&did)
2015 && let hash_set::Entry::Vacant(v) =
2016 previously_seen_dids.entry(parent)
2017 {
2018 if self.tcx.is_doc_hidden(did) {
2019 return false;
2020 }
2021 v.insert();
2022 did = parent;
2023 }
2024 }
2025 true
2026 } else {
2027 false
2028 }
2029 } else {
2030 true
2031 }
2032 })
2033 .collect();
2034
2035 impl_candidates.sort_by_key(|(tr, _)| tr.to_string());
2036 impl_candidates.dedup();
2037 impl_candidates
2038 };
2039
2040 if let [single] = &impl_candidates {
2041 let self_ty = trait_pred.skip_binder().self_ty();
2042 if !self_ty.has_escaping_bound_vars() {
2043 let self_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
2044 if let ty::Ref(_, inner_ty, _) = self_ty.kind()
2045 && self.can_eq(param_env, single.trait_ref.self_ty(), *inner_ty)
2046 && !self.where_clause_expr_matches_failed_self_ty(obligation, self_ty)
2047 {
2048 return true;
2052 }
2053 }
2054
2055 if self.probe(|_| {
2058 let ocx = ObligationCtxt::new(self);
2059
2060 self.enter_forall(trait_pred, |obligation_trait_ref| {
2061 let impl_args = self.fresh_args_for_item(DUMMY_SP, single.impl_def_id);
2062 let impl_trait_ref = ocx.normalize(
2063 &ObligationCause::dummy(),
2064 param_env,
2065 ty::EarlyBinder::bind(single.trait_ref).instantiate(self.tcx, impl_args),
2066 );
2067
2068 ocx.register_obligations(
2069 self.tcx
2070 .predicates_of(single.impl_def_id)
2071 .instantiate(self.tcx, impl_args)
2072 .into_iter()
2073 .map(|(clause, _)| {
2074 Obligation::new(
2075 self.tcx,
2076 ObligationCause::dummy(),
2077 param_env,
2078 clause.skip_norm_wip(),
2079 )
2080 }),
2081 );
2082 if !ocx.try_evaluate_obligations().is_empty() {
2083 return false;
2084 }
2085
2086 let mut terrs = ::alloc::vec::Vec::new()vec![];
2087 for (obligation_arg, impl_arg) in
2088 std::iter::zip(obligation_trait_ref.trait_ref.args, impl_trait_ref.args)
2089 {
2090 if (obligation_arg, impl_arg).references_error() {
2091 return false;
2092 }
2093 if let Err(terr) =
2094 ocx.eq(&ObligationCause::dummy(), param_env, impl_arg, obligation_arg)
2095 {
2096 terrs.push(terr);
2097 }
2098 if !ocx.try_evaluate_obligations().is_empty() {
2099 return false;
2100 }
2101 }
2102
2103 if terrs.len() == impl_trait_ref.args.len() {
2105 return false;
2106 }
2107
2108 let impl_trait_ref = self.resolve_vars_if_possible(impl_trait_ref);
2109 if impl_trait_ref.references_error() {
2110 return false;
2111 }
2112
2113 if let [child, ..] = &err.children[..]
2114 && child.level == Level::Help
2115 && let Some(line) = child.messages.get(0)
2116 && let Some(line) = line.0.as_str()
2117 && line.starts_with("the trait")
2118 && line.contains("is not implemented for")
2119 {
2120 err.children.remove(0);
2127 }
2128
2129 let traits = self.cmp_traits(
2130 obligation_trait_ref.def_id(),
2131 &obligation_trait_ref.trait_ref.args[1..],
2132 impl_trait_ref.def_id,
2133 &impl_trait_ref.args[1..],
2134 );
2135 let traits_content = (traits.0.content(), traits.1.content());
2136 let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty());
2137 let types_content = (types.0.content(), types.1.content());
2138 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 `")];
2139 if traits_content.0 == traits_content.1 {
2140 msg.push(StringPart::normal(
2141 impl_trait_ref.print_trait_sugared().to_string(),
2142 ));
2143 } else {
2144 msg.extend(traits.0.0);
2145 }
2146 msg.extend([
2147 StringPart::normal("` "),
2148 StringPart::highlighted("is not"),
2149 StringPart::normal(" implemented for `"),
2150 ]);
2151 if types_content.0 == types_content.1 {
2152 let ty = self
2153 .tcx
2154 .short_string(obligation_trait_ref.self_ty(), err.long_ty_path());
2155 msg.push(StringPart::normal(ty));
2156 } else {
2157 msg.extend(types.0.0);
2158 }
2159 msg.push(StringPart::normal("`"));
2160 if types_content.0 == types_content.1 {
2161 msg.push(StringPart::normal("\nbut trait `"));
2162 msg.extend(traits.1.0);
2163 msg.extend([
2164 StringPart::normal("` "),
2165 StringPart::highlighted("is"),
2166 StringPart::normal(" implemented for it"),
2167 ]);
2168 } else if traits_content.0 == traits_content.1 {
2169 msg.extend([
2170 StringPart::normal("\nbut it "),
2171 StringPart::highlighted("is"),
2172 StringPart::normal(" implemented for `"),
2173 ]);
2174 msg.extend(types.1.0);
2175 msg.push(StringPart::normal("`"));
2176 } else {
2177 msg.push(StringPart::normal("\nbut trait `"));
2178 msg.extend(traits.1.0);
2179 msg.extend([
2180 StringPart::normal("` "),
2181 StringPart::highlighted("is"),
2182 StringPart::normal(" implemented for `"),
2183 ]);
2184 msg.extend(types.1.0);
2185 msg.push(StringPart::normal("`"));
2186 }
2187 err.highlighted_span_help(self.tcx.def_span(single.impl_def_id), msg);
2188
2189 if let [TypeError::Sorts(exp_found)] = &terrs[..] {
2190 let exp_found = self.resolve_vars_if_possible(*exp_found);
2191 let expected =
2192 self.tcx.short_string(exp_found.expected, err.long_ty_path());
2193 let found = self.tcx.short_string(exp_found.found, err.long_ty_path());
2194 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![
2195 StringPart::normal("for that trait implementation, "),
2196 StringPart::normal("expected `"),
2197 StringPart::highlighted(expected),
2198 StringPart::normal("`, found `"),
2199 StringPart::highlighted(found),
2200 StringPart::normal("`"),
2201 ]);
2202 self.suggest_function_pointers_impl(None, &exp_found, err);
2203 }
2204
2205 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2206 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2207 && !crates.is_empty()
2208 {
2209 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2210 err.help("you can use `cargo tree` to explore your dependency tree");
2211 }
2212 true
2213 })
2214 }) {
2215 return true;
2216 }
2217 }
2218
2219 let other = if other { "other " } else { "" };
2220 let report = |mut candidates: Vec<(TraitRef<'tcx>, DefId)>, err: &mut Diag<'_>| {
2221 candidates.retain(|(tr, _)| !tr.references_error());
2222 if candidates.is_empty() {
2223 return false;
2224 }
2225 let mut specific_candidates = candidates.clone();
2226 specific_candidates.retain(|(tr, _)| {
2227 tr.with_replaced_self_ty(self.tcx, trait_pred.skip_binder().self_ty())
2228 == trait_pred.skip_binder().trait_ref
2229 });
2230 if !specific_candidates.is_empty() {
2231 candidates = specific_candidates;
2234 }
2235 if let &[(cand, def_id)] = &candidates[..] {
2236 if self.tcx.is_diagnostic_item(sym::FromResidual, cand.def_id)
2237 && !self.tcx.features().enabled(sym::try_trait_v2)
2238 {
2239 return false;
2240 }
2241 let (desc, mention_castable) =
2242 match (cand.self_ty().kind(), trait_pred.self_ty().skip_binder().kind()) {
2243 (ty::FnPtr(..), ty::FnDef(..)) => {
2244 (" implemented for fn pointer `", ", cast using `as`")
2245 }
2246 (ty::FnPtr(..), _) => (" implemented for fn pointer `", ""),
2247 _ => (" implemented for `", ""),
2248 };
2249 let trait_ = self.tcx.short_string(cand.print_trait_sugared(), err.long_ty_path());
2250 let self_ty = self.tcx.short_string(cand.self_ty(), err.long_ty_path());
2251 err.highlighted_span_help(
2252 self.tcx.def_span(def_id),
2253 ::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![
2254 StringPart::normal(format!("the trait `{trait_}` ")),
2255 StringPart::highlighted("is"),
2256 StringPart::normal(desc),
2257 StringPart::highlighted(self_ty),
2258 StringPart::normal("`"),
2259 StringPart::normal(mention_castable),
2260 ],
2261 );
2262 return true;
2263 }
2264 let trait_ref = TraitRef::identity(self.tcx, candidates[0].0.def_id);
2265 let mut traits: Vec<_> =
2267 candidates.iter().map(|(c, _)| c.print_only_trait_path().to_string()).collect();
2268 traits.sort();
2269 traits.dedup();
2270 let all_traits_equal = traits.len() == 1;
2273 let mut types: Vec<_> =
2274 candidates.iter().map(|(c, _)| c.self_ty().to_string()).collect();
2275 types.sort();
2276 types.dedup();
2277 let all_types_equal = types.len() == 1;
2278
2279 let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose {
2280 candidates.len()
2281 } else {
2282 8
2283 };
2284 if candidates.len() < 5 {
2285 let spans: Vec<_> =
2286 candidates.iter().map(|&(_, def_id)| self.tcx.def_span(def_id)).collect();
2287 let mut span: MultiSpan = spans.into();
2288 for (c, def_id) in &candidates {
2289 let msg = if all_traits_equal {
2290 ::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()))
2291 } else if all_types_equal {
2292 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2293 "`{}`",
2294 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path())
2295 )
2296 } else {
2297 ::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!(
2298 "`{}` implements `{}`",
2299 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2300 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path()),
2301 )
2302 };
2303 span.push_span_label(self.tcx.def_span(*def_id), msg);
2304 }
2305 let msg = if all_types_equal {
2306 ::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!(
2307 "`{}` implements trait `{}`",
2308 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2309 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2310 )
2311 } else {
2312 ::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!(
2313 "the following {other}types implement trait `{}`",
2314 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2315 )
2316 };
2317 err.span_help(span, msg);
2318 } else {
2319 let candidate_names: Vec<String> = candidates
2320 .iter()
2321 .map(|(c, _)| {
2322 if all_traits_equal {
2323 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n {0}",
self.tcx.short_string(c.self_ty(), err.long_ty_path())))
})format!(
2324 "\n {}",
2325 self.tcx.short_string(c.self_ty(), err.long_ty_path())
2326 )
2327 } else if all_types_equal {
2328 ::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!(
2329 "\n {}",
2330 self.tcx
2331 .short_string(c.print_only_trait_path(), err.long_ty_path())
2332 )
2333 } else {
2334 ::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!(
2335 "\n `{}` implements `{}`",
2336 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2337 self.tcx
2338 .short_string(c.print_only_trait_path(), err.long_ty_path()),
2339 )
2340 }
2341 })
2342 .collect();
2343 let msg = if all_types_equal {
2344 ::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!(
2345 "`{}` implements trait `{}`",
2346 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2347 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2348 )
2349 } else {
2350 ::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!(
2351 "the following {other}types implement trait `{}`",
2352 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2353 )
2354 };
2355
2356 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!(
2357 "{msg}:{}{}",
2358 candidate_names[..end].join(""),
2359 if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
2360 format!("\nand {} others", candidates.len() - 8)
2361 } else {
2362 String::new()
2363 }
2364 ));
2365 }
2366
2367 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2368 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2369 && !crates.is_empty()
2370 {
2371 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2372 err.help("you can use `cargo tree` to explore your dependency tree");
2373 }
2374 true
2375 };
2376
2377 let impl_candidates = impl_candidates
2380 .into_iter()
2381 .cloned()
2382 .filter(|cand| !self.tcx.do_not_recommend_impl(cand.impl_def_id))
2383 .collect::<Vec<_>>();
2384
2385 let def_id = trait_pred.def_id();
2386 if impl_candidates.is_empty() {
2387 if self.tcx.trait_is_auto(def_id)
2388 || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2389 || self.tcx.get_diagnostic_name(def_id).is_some()
2390 {
2391 return false;
2393 }
2394 return report(alternative_candidates(def_id), err);
2395 }
2396
2397 let mut impl_candidates: Vec<_> = impl_candidates
2404 .iter()
2405 .cloned()
2406 .filter(|cand| !cand.trait_ref.references_error())
2407 .map(|mut cand| {
2408 cand.trait_ref = self
2412 .tcx
2413 .try_normalize_erasing_regions(
2414 ty::TypingEnv::non_body_analysis(self.tcx, cand.impl_def_id),
2415 Unnormalized::new_wip(cand.trait_ref),
2416 )
2417 .unwrap_or(cand.trait_ref);
2418 cand
2419 })
2420 .collect();
2421 impl_candidates.sort_by_key(|cand| {
2422 let len = if let GenericArgKind::Type(ty) = cand.trait_ref.args[0].kind()
2424 && let ty::Array(_, len) = ty.kind()
2425 {
2426 len.try_to_target_usize(self.tcx).unwrap_or(u64::MAX)
2428 } else {
2429 0
2430 };
2431
2432 (cand.similarity, len, cand.trait_ref.to_string())
2433 });
2434 let mut impl_candidates: Vec<_> =
2435 impl_candidates.into_iter().map(|cand| (cand.trait_ref, cand.impl_def_id)).collect();
2436 impl_candidates.dedup();
2437
2438 report(impl_candidates, err)
2439 }
2440
2441 fn report_similar_impl_candidates_for_root_obligation(
2442 &self,
2443 obligation: &PredicateObligation<'tcx>,
2444 trait_predicate: ty::Binder<'tcx, ty::TraitPredicate<'tcx>>,
2445 body_def_id: LocalDefId,
2446 err: &mut Diag<'_>,
2447 ) {
2448 let mut code = obligation.cause.code();
2455 let mut trait_pred = trait_predicate;
2456 let mut peeled = false;
2457 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
2458 code = parent_code;
2459 if let Some(parent_trait_pred) = parent_trait_pred {
2460 trait_pred = parent_trait_pred;
2461 peeled = true;
2462 }
2463 }
2464 let def_id = trait_pred.def_id();
2465 if peeled && !self.tcx.trait_is_auto(def_id) && self.tcx.as_lang_item(def_id).is_none() {
2471 let impl_candidates = self.find_similar_impl_candidates(trait_pred);
2472 self.report_similar_impl_candidates(
2473 &impl_candidates,
2474 obligation,
2475 trait_pred,
2476 body_def_id,
2477 err,
2478 true,
2479 obligation.param_env,
2480 );
2481 }
2482 }
2483
2484 fn get_parent_trait_ref(
2486 &self,
2487 code: &ObligationCauseCode<'tcx>,
2488 ) -> Option<(Ty<'tcx>, Option<Span>)> {
2489 match code {
2490 ObligationCauseCode::BuiltinDerived(data) => {
2491 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2492 match self.get_parent_trait_ref(&data.parent_code) {
2493 Some(t) => Some(t),
2494 None => {
2495 let ty = parent_trait_ref.skip_binder().self_ty();
2496 let span = TyCategory::from_ty(self.tcx, ty)
2497 .map(|(_, def_id)| self.tcx.def_span(def_id));
2498 Some((ty, span))
2499 }
2500 }
2501 }
2502 ObligationCauseCode::FunctionArg { parent_code, .. } => {
2503 self.get_parent_trait_ref(parent_code)
2504 }
2505 _ => None,
2506 }
2507 }
2508
2509 fn check_same_trait_different_version(
2510 &self,
2511 err: &mut Diag<'_>,
2512 trait_pred: ty::PolyTraitPredicate<'tcx>,
2513 ) -> bool {
2514 let get_trait_impls = |trait_def_id| {
2515 let mut trait_impls = ::alloc::vec::Vec::new()vec![];
2516 self.tcx.for_each_relevant_impl(
2517 trait_def_id,
2518 trait_pred.skip_binder().self_ty(),
2519 |impl_def_id| {
2520 let impl_trait_header = self.tcx.impl_trait_header(impl_def_id);
2521 trait_impls
2522 .push(self.tcx.def_span(impl_trait_header.trait_ref.skip_binder().def_id));
2523 },
2524 );
2525 trait_impls
2526 };
2527 self.check_same_definition_different_crate(
2528 err,
2529 trait_pred.def_id(),
2530 self.tcx.visible_traits(),
2531 get_trait_impls,
2532 "trait",
2533 )
2534 }
2535
2536 pub fn note_two_crate_versions(
2537 &self,
2538 krate: CrateNum,
2539 sp: impl Into<MultiSpan>,
2540 err: &mut Diag<'_>,
2541 ) {
2542 let crate_name = self.tcx.crate_name(krate);
2543 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!(
2544 "there are multiple different versions of crate `{crate_name}` in the dependency graph"
2545 );
2546 err.span_note(sp, crate_msg);
2547 }
2548
2549 fn note_adt_version_mismatch(
2550 &self,
2551 err: &mut Diag<'_>,
2552 trait_pred: ty::PolyTraitPredicate<'tcx>,
2553 ) {
2554 let ty::Adt(impl_self_def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2555 else {
2556 return;
2557 };
2558
2559 let impl_self_did = impl_self_def.did();
2560
2561 if impl_self_did.krate == LOCAL_CRATE {
2564 return;
2565 }
2566
2567 let impl_self_path = self.comparable_path(impl_self_did);
2568 let impl_self_crate_name = self.tcx.crate_name(impl_self_did.krate);
2569 let similar_items: UnordSet<_> = self
2570 .tcx
2571 .visible_parent_map(())
2572 .items()
2573 .filter_map(|(&item, _)| {
2574 if impl_self_did == item {
2576 return None;
2577 }
2578 if item.krate == LOCAL_CRATE {
2581 return None;
2582 }
2583 if impl_self_crate_name != self.tcx.crate_name(item.krate) {
2586 return None;
2587 }
2588 if !self.tcx.def_kind(item).is_adt() {
2591 return None;
2592 }
2593 let path = self.comparable_path(item);
2594 let is_similar = path.ends_with(&impl_self_path) || impl_self_path.ends_with(&path);
2597 is_similar.then_some((item, path))
2598 })
2599 .collect();
2600
2601 let mut similar_items =
2602 similar_items.into_items().into_sorted_stable_ord_by_key(|(_, path)| path);
2603 similar_items.dedup();
2604
2605 for (similar_item, _) in similar_items {
2606 err.span_help(self.tcx.def_span(similar_item), "item with same name found");
2607 self.note_two_crate_versions(similar_item.krate, MultiSpan::new(), err);
2608 }
2609 }
2610
2611 fn check_same_name_different_path(
2612 &self,
2613 err: &mut Diag<'_>,
2614 obligation: &PredicateObligation<'tcx>,
2615 trait_pred: ty::PolyTraitPredicate<'tcx>,
2616 ) -> bool {
2617 let mut suggested = false;
2618 let trait_def_id = trait_pred.def_id();
2619 let trait_has_same_params = |other_trait_def_id: DefId| -> bool {
2620 let trait_generics = self.tcx.generics_of(trait_def_id);
2621 let other_trait_generics = self.tcx.generics_of(other_trait_def_id);
2622
2623 if trait_generics.count() != other_trait_generics.count() {
2624 return false;
2625 }
2626 trait_generics.own_params.iter().zip(other_trait_generics.own_params.iter()).all(
2627 |(a, b)| match (&a.kind, &b.kind) {
2628 (ty::GenericParamDefKind::Lifetime, ty::GenericParamDefKind::Lifetime)
2629 | (
2630 ty::GenericParamDefKind::Type { .. },
2631 ty::GenericParamDefKind::Type { .. },
2632 )
2633 | (
2634 ty::GenericParamDefKind::Const { .. },
2635 ty::GenericParamDefKind::Const { .. },
2636 ) => true,
2637 _ => false,
2638 },
2639 )
2640 };
2641 let trait_name = self.tcx.item_name(trait_def_id);
2642 if let Some(other_trait_def_id) = self.tcx.all_traits_including_private().find(|&def_id| {
2643 trait_def_id != def_id
2644 && trait_name == self.tcx.item_name(def_id)
2645 && trait_has_same_params(def_id)
2646 && !self.tcx.is_lang_item(def_id, LangItem::PointeeSized)
2648 && self.predicate_must_hold_modulo_regions(&Obligation::new(
2649 self.tcx,
2650 obligation.cause.clone(),
2651 obligation.param_env,
2652 trait_pred.map_bound(|tr| ty::TraitPredicate {
2653 trait_ref: ty::TraitRef::new(self.tcx, def_id, tr.trait_ref.args),
2654 ..tr
2655 }),
2656 ))
2657 }) {
2658 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!(
2659 "`{}` implements similarly named trait `{}`, but not `{}`",
2660 trait_pred.self_ty(),
2661 self.tcx.def_path_str(other_trait_def_id),
2662 trait_pred.print_modifiers_and_trait_path()
2663 ));
2664 suggested = true;
2665 }
2666 suggested
2667 }
2668
2669 pub fn note_different_trait_with_same_name(
2674 &self,
2675 err: &mut Diag<'_>,
2676 obligation: &PredicateObligation<'tcx>,
2677 trait_pred: ty::PolyTraitPredicate<'tcx>,
2678 ) -> bool {
2679 if self.check_same_trait_different_version(err, trait_pred) {
2680 return true;
2681 }
2682 self.check_same_name_different_path(err, obligation, trait_pred)
2683 }
2684
2685 fn comparable_path(&self, did: DefId) -> String {
2688 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}",
self.tcx.def_path_str(did)))
})format!("::{}", self.tcx.def_path_str(did))
2689 }
2690
2691 pub(super) fn mk_trait_obligation_with_new_self_ty(
2696 &self,
2697 param_env: ty::ParamEnv<'tcx>,
2698 trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitPredicate<'tcx>, Ty<'tcx>)>,
2699 ) -> PredicateObligation<'tcx> {
2700 let trait_pred = trait_ref_and_ty
2701 .map_bound(|(tr, new_self_ty)| tr.with_replaced_self_ty(self.tcx, new_self_ty));
2702
2703 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
2704 }
2705
2706 fn predicate_can_apply(
2709 &self,
2710 param_env: ty::ParamEnv<'tcx>,
2711 pred: ty::PolyTraitPredicate<'tcx>,
2712 ) -> bool {
2713 struct ParamToVarFolder<'a, 'tcx> {
2714 infcx: &'a InferCtxt<'tcx>,
2715 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
2716 }
2717
2718 impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
2719 fn cx(&self) -> TyCtxt<'tcx> {
2720 self.infcx.tcx
2721 }
2722
2723 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
2724 if let ty::Param(_) = *ty.kind() {
2725 let infcx = self.infcx;
2726 *self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
2727 } else {
2728 ty.super_fold_with(self)
2729 }
2730 }
2731 }
2732
2733 self.probe(|_| {
2734 let cleaned_pred =
2735 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
2736
2737 let InferOk { value: cleaned_pred, .. } = self
2738 .infcx
2739 .at(&ObligationCause::dummy(), param_env)
2740 .normalize(Unnormalized::new_wip(cleaned_pred));
2741
2742 let obligation =
2743 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
2744
2745 self.predicate_may_hold(&obligation)
2746 })
2747 }
2748
2749 pub fn note_obligation_cause(
2750 &self,
2751 err: &mut Diag<'_>,
2752 obligation: &PredicateObligation<'tcx>,
2753 ) {
2754 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
2757 self.note_obligation_cause_code(
2758 obligation.cause.body_id,
2759 err,
2760 obligation.predicate,
2761 obligation.param_env,
2762 obligation.cause.code(),
2763 &mut ::alloc::vec::Vec::new()vec![],
2764 &mut Default::default(),
2765 );
2766 self.suggest_swapping_lhs_and_rhs(
2767 err,
2768 obligation.predicate,
2769 obligation.param_env,
2770 obligation.cause.code(),
2771 );
2772 self.suggest_borrow_for_unsized_closure_return(
2773 obligation.cause.body_id,
2774 err,
2775 obligation.predicate,
2776 );
2777 self.suggest_unsized_bound_if_applicable(err, obligation);
2778 if let Some(span) = err.span.primary_span()
2779 && let Some(mut diag) =
2780 self.dcx().steal_non_err(span, StashKey::AssociatedTypeSuggestion)
2781 && let Suggestions::Enabled(ref mut s1) = err.suggestions
2782 && let Suggestions::Enabled(ref mut s2) = diag.suggestions
2783 {
2784 s1.append(s2);
2785 diag.cancel()
2786 }
2787 }
2788 }
2789
2790 pub(super) fn is_recursive_obligation(
2791 &self,
2792 obligated_types: &mut Vec<Ty<'tcx>>,
2793 cause_code: &ObligationCauseCode<'tcx>,
2794 ) -> bool {
2795 if let ObligationCauseCode::BuiltinDerived(data) = cause_code {
2796 let parent_trait_ref = self.resolve_vars_if_possible(data.parent_trait_pred);
2797 let self_ty = parent_trait_ref.skip_binder().self_ty();
2798 if obligated_types.iter().any(|ot| ot == &self_ty) {
2799 return true;
2800 }
2801 if let ty::Adt(def, args) = self_ty.kind()
2802 && let [arg] = &args[..]
2803 && let ty::GenericArgKind::Type(ty) = arg.kind()
2804 && let ty::Adt(inner_def, _) = ty.kind()
2805 && inner_def == def
2806 {
2807 return true;
2808 }
2809 }
2810 false
2811 }
2812
2813 fn get_standard_error_message(
2814 &self,
2815 trait_predicate: ty::PolyTraitPredicate<'tcx>,
2816 predicate_constness: Option<ty::BoundConstness>,
2817 post_message: String,
2818 long_ty_path: &mut Option<PathBuf>,
2819 ) -> String {
2820 ::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!(
2821 "the trait bound `{}` is not satisfied{post_message}",
2822 self.tcx.short_string(
2823 trait_predicate.print_with_bound_constness(predicate_constness),
2824 long_ty_path,
2825 ),
2826 )
2827 }
2828
2829 fn select_transmute_obligation_for_reporting(
2830 &self,
2831 obligation: &PredicateObligation<'tcx>,
2832 trait_predicate: ty::PolyTraitPredicate<'tcx>,
2833 root_obligation: &PredicateObligation<'tcx>,
2834 ) -> (PredicateObligation<'tcx>, ty::PolyTraitPredicate<'tcx>) {
2835 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
2836 return (obligation.clone(), trait_predicate);
2837 }
2838
2839 let ocx = ObligationCtxt::new(self);
2840 let normalized_predicate = self.tcx.erase_and_anonymize_regions(
2841 self.tcx.instantiate_bound_regions_with_erased(trait_predicate),
2842 );
2843 let trait_ref = normalized_predicate.trait_ref;
2844
2845 let Ok(assume) = ocx.structurally_normalize_const(
2846 &obligation.cause,
2847 obligation.param_env,
2848 Unnormalized::new_wip(trait_ref.args.const_at(2)),
2849 ) else {
2850 return (obligation.clone(), trait_predicate);
2851 };
2852
2853 let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
2854 return (obligation.clone(), trait_predicate);
2855 };
2856
2857 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!(
2858 rustc_transmute::TransmuteTypeEnv::new(self.tcx).is_transmutable(
2859 trait_ref.args.type_at(1),
2860 trait_ref.args.type_at(0),
2861 assume,
2862 ),
2863 rustc_transmute::Answer::Yes,
2864 );
2865
2866 if is_normalized_yes
2868 && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
2869 root_obligation.predicate.kind().skip_binder()
2870 && root_pred.def_id() == trait_predicate.def_id()
2871 {
2872 return (root_obligation.clone(), root_obligation.predicate.kind().rebind(root_pred));
2873 }
2874
2875 (obligation.clone(), trait_predicate)
2876 }
2877
2878 fn get_safe_transmute_error_and_reason(
2879 &self,
2880 obligation: PredicateObligation<'tcx>,
2881 trait_pred: ty::PolyTraitPredicate<'tcx>,
2882 span: Span,
2883 ) -> GetSafeTransmuteErrorAndReason {
2884 use rustc_transmute::Answer;
2885 self.probe(|_| {
2886 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
2889 return GetSafeTransmuteErrorAndReason::Default;
2890 }
2891
2892 let trait_pred = self.tcx.erase_and_anonymize_regions(
2894 self.tcx.instantiate_bound_regions_with_erased(trait_pred),
2895 );
2896
2897 let ocx = ObligationCtxt::new(self);
2898 let Ok(assume) = ocx.structurally_normalize_const(
2899 &obligation.cause,
2900 obligation.param_env,
2901 Unnormalized::new_wip(trait_pred.trait_ref.args.const_at(2)),
2902 ) else {
2903 self.dcx().span_delayed_bug(
2904 span,
2905 "Unable to construct rustc_transmute::Assume where it was previously possible",
2906 );
2907 return GetSafeTransmuteErrorAndReason::Silent;
2908 };
2909
2910 let Some(assume) = rustc_transmute::Assume::from_const(self.infcx.tcx, assume) else {
2911 self.dcx().span_delayed_bug(
2912 span,
2913 "Unable to construct rustc_transmute::Assume where it was previously possible",
2914 );
2915 return GetSafeTransmuteErrorAndReason::Silent;
2916 };
2917
2918 let dst = trait_pred.trait_ref.args.type_at(0);
2919 let src = trait_pred.trait_ref.args.type_at(1);
2920 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}`");
2921
2922 match rustc_transmute::TransmuteTypeEnv::new(self.infcx.tcx)
2923 .is_transmutable(src, dst, assume)
2924 {
2925 Answer::No(reason) => {
2926 let safe_transmute_explanation = match reason {
2927 rustc_transmute::Reason::SrcIsNotYetSupported => {
2928 ::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")
2929 }
2930 rustc_transmute::Reason::DstIsNotYetSupported => {
2931 ::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")
2932 }
2933 rustc_transmute::Reason::DstIsBitIncompatible => {
2934 ::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!(
2935 "at least one value of `{src}` isn't a bit-valid value of `{dst}`"
2936 )
2937 }
2938 rustc_transmute::Reason::DstUninhabited => {
2939 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is uninhabited", dst))
})format!("`{dst}` is uninhabited")
2940 }
2941 rustc_transmute::Reason::DstMayHaveSafetyInvariants => {
2942 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` may carry safety invariants",
dst))
})format!("`{dst}` may carry safety invariants")
2943 }
2944 rustc_transmute::Reason::DstIsTooBig => {
2945 ::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}`")
2946 }
2947 rustc_transmute::Reason::DstRefIsTooBig {
2948 src,
2949 src_size,
2950 dst,
2951 dst_size,
2952 } => {
2953 ::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!(
2954 "the size of `{src}` ({src_size} bytes) \
2955 is smaller than that of `{dst}` ({dst_size} bytes)"
2956 )
2957 }
2958 rustc_transmute::Reason::SrcSizeOverflow => {
2959 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
src))
})format!(
2960 "values of the type `{src}` are too big for the target architecture"
2961 )
2962 }
2963 rustc_transmute::Reason::DstSizeOverflow => {
2964 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
dst))
})format!(
2965 "values of the type `{dst}` are too big for the target architecture"
2966 )
2967 }
2968 rustc_transmute::Reason::DstHasStricterAlignment {
2969 src_min_align,
2970 dst_min_align,
2971 } => {
2972 ::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!(
2973 "the minimum alignment of `{src}` ({src_min_align}) should be \
2974 greater than that of `{dst}` ({dst_min_align})"
2975 )
2976 }
2977 rustc_transmute::Reason::DstIsMoreUnique => {
2978 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is a shared reference, but `{1}` is a unique reference",
src, dst))
})format!(
2979 "`{src}` is a shared reference, but `{dst}` is a unique reference"
2980 )
2981 }
2982 rustc_transmute::Reason::TypeError => {
2984 return GetSafeTransmuteErrorAndReason::Silent;
2985 }
2986 rustc_transmute::Reason::SrcLayoutUnknown => {
2987 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", src))
})format!("`{src}` has an unknown layout")
2988 }
2989 rustc_transmute::Reason::DstLayoutUnknown => {
2990 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", dst))
})format!("`{dst}` has an unknown layout")
2991 }
2992 };
2993 GetSafeTransmuteErrorAndReason::Error {
2994 err_msg,
2995 safe_transmute_explanation: Some(safe_transmute_explanation),
2996 }
2997 }
2998 Answer::Yes => ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("Inconsistent rustc_transmute::is_transmutable(...) result, got Yes"))span_bug!(
3000 span,
3001 "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
3002 ),
3003 Answer::If(_) => GetSafeTransmuteErrorAndReason::Error {
3008 err_msg,
3009 safe_transmute_explanation: None,
3010 },
3011 }
3012 })
3013 }
3014
3015 fn find_explicit_cast_type(
3018 &self,
3019 param_env: ty::ParamEnv<'tcx>,
3020 found_ty: Ty<'tcx>,
3021 self_ty: Ty<'tcx>,
3022 ) -> Option<Ty<'tcx>> {
3023 let ty::Ref(region, inner_ty, mutbl) = *found_ty.kind() else {
3024 return None;
3025 };
3026
3027 let mut derefs = (self.autoderef_steps)(inner_ty).into_iter();
3028 derefs.next(); let deref_target = derefs.into_iter().next()?.0;
3030
3031 let cast_ty = Ty::new_ref(self.tcx, region, deref_target, mutbl);
3032
3033 let Some(from_def_id) = self.tcx.get_diagnostic_item(sym::From) else {
3034 return None;
3035 };
3036 let Some(try_from_def_id) = self.tcx.get_diagnostic_item(sym::TryFrom) else {
3037 return None;
3038 };
3039
3040 if self.has_impl_for_type(
3041 param_env,
3042 ty::TraitRef::new(
3043 self.tcx,
3044 from_def_id,
3045 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3046 ),
3047 ) {
3048 Some(cast_ty)
3049 } else if self.has_impl_for_type(
3050 param_env,
3051 ty::TraitRef::new(
3052 self.tcx,
3053 try_from_def_id,
3054 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3055 ),
3056 ) {
3057 Some(cast_ty)
3058 } else {
3059 None
3060 }
3061 }
3062
3063 fn has_impl_for_type(
3064 &self,
3065 param_env: ty::ParamEnv<'tcx>,
3066 trait_ref: ty::TraitRef<'tcx>,
3067 ) -> bool {
3068 let obligation = Obligation::new(
3069 self.tcx,
3070 ObligationCause::dummy(),
3071 param_env,
3072 ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Positive },
3073 );
3074
3075 self.predicate_must_hold_modulo_regions(&obligation)
3076 }
3077
3078 fn add_tuple_trait_message(
3079 &self,
3080 obligation_cause_code: &ObligationCauseCode<'tcx>,
3081 err: &mut Diag<'_>,
3082 ) {
3083 match obligation_cause_code {
3084 ObligationCauseCode::RustCall => {
3085 err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
3086 }
3087 ObligationCauseCode::WhereClause(def_id, _) if self.tcx.is_fn_trait(*def_id) => {
3088 err.code(E0059);
3089 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!(
3090 "type parameter to bare `{}` trait must be a tuple",
3091 self.tcx.def_path_str(*def_id)
3092 ));
3093 }
3094 _ => {}
3095 }
3096 }
3097
3098 fn try_to_add_help_message(
3099 &self,
3100 root_obligation: &PredicateObligation<'tcx>,
3101 obligation: &PredicateObligation<'tcx>,
3102 trait_predicate: ty::PolyTraitPredicate<'tcx>,
3103 err: &mut Diag<'_>,
3104 span: Span,
3105 is_fn_trait: bool,
3106 suggested: bool,
3107 ) {
3108 let body_def_id = obligation.cause.body_id;
3109 let span = if let ObligationCauseCode::BinOp { rhs_span, .. } = obligation.cause.code() {
3110 *rhs_span
3111 } else {
3112 span
3113 };
3114
3115 let trait_def_id = trait_predicate.def_id();
3117 if is_fn_trait
3118 && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
3119 obligation.param_env,
3120 trait_predicate.self_ty(),
3121 trait_predicate.skip_binder().polarity,
3122 )
3123 {
3124 self.add_help_message_for_fn_trait(trait_predicate, err, implemented_kind, params);
3125 } else if !trait_predicate.has_non_region_infer()
3126 && self.predicate_can_apply(obligation.param_env, trait_predicate)
3127 {
3128 self.suggest_restricting_param_bound(
3136 err,
3137 trait_predicate,
3138 None,
3139 obligation.cause.body_id,
3140 );
3141 } else if trait_def_id.is_local()
3142 && self.tcx.trait_impls_of(trait_def_id).is_empty()
3143 && !self.tcx.trait_is_auto(trait_def_id)
3144 && !self.tcx.trait_is_alias(trait_def_id)
3145 && trait_predicate.polarity() == ty::PredicatePolarity::Positive
3146 {
3147 err.span_help(
3148 self.tcx.def_span(trait_def_id),
3149 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"),
3150 );
3151 } else if !suggested && trait_predicate.polarity() == ty::PredicatePolarity::Positive {
3152 let impl_candidates = self.find_similar_impl_candidates(trait_predicate);
3154 if !self.report_similar_impl_candidates(
3155 &impl_candidates,
3156 obligation,
3157 trait_predicate,
3158 body_def_id,
3159 err,
3160 true,
3161 obligation.param_env,
3162 ) {
3163 self.report_similar_impl_candidates_for_root_obligation(
3164 obligation,
3165 trait_predicate,
3166 body_def_id,
3167 err,
3168 );
3169 }
3170
3171 self.suggest_convert_to_slice(
3172 err,
3173 obligation,
3174 trait_predicate,
3175 impl_candidates.as_slice(),
3176 span,
3177 );
3178
3179 self.suggest_tuple_wrapping(err, root_obligation, obligation);
3180 }
3181 self.suggest_shadowed_inherent_method(err, obligation, trait_predicate);
3182 }
3183
3184 fn add_help_message_for_fn_trait(
3185 &self,
3186 trait_pred: ty::PolyTraitPredicate<'tcx>,
3187 err: &mut Diag<'_>,
3188 implemented_kind: ty::ClosureKind,
3189 params: ty::Binder<'tcx, Ty<'tcx>>,
3190 ) {
3191 let selected_kind = self
3198 .tcx
3199 .fn_trait_kind_from_def_id(trait_pred.def_id())
3200 .expect("expected to map DefId to ClosureKind");
3201 if !implemented_kind.extends(selected_kind) {
3202 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!(
3203 "`{}` implements `{}`, but it must implement `{}`, which is more general",
3204 trait_pred.skip_binder().self_ty(),
3205 implemented_kind,
3206 selected_kind
3207 ));
3208 }
3209
3210 let ty::Tuple(given) = *params.skip_binder().kind() else {
3212 return;
3213 };
3214
3215 let expected_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
3216 let ty::Tuple(expected) = *expected_ty.kind() else {
3217 return;
3218 };
3219
3220 if expected.len() != given.len() {
3221 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!(
3223 "expected a closure taking {} argument{}, but one taking {} argument{} was given",
3224 given.len(),
3225 pluralize!(given.len()),
3226 expected.len(),
3227 pluralize!(expected.len()),
3228 ));
3229 return;
3230 }
3231
3232 let given_ty = Ty::new_fn_ptr(
3233 self.tcx,
3234 params.rebind(self.tcx.mk_fn_sig_safe_rust_abi(given, self.tcx.types.unit)),
3235 );
3236 let expected_ty = Ty::new_fn_ptr(
3237 self.tcx,
3238 trait_pred.rebind(self.tcx.mk_fn_sig_safe_rust_abi(expected, self.tcx.types.unit)),
3239 );
3240
3241 if !self.same_type_modulo_infer(given_ty, expected_ty) {
3242 let (expected_args, given_args) = self.cmp(expected_ty, given_ty);
3244 err.note_expected_found(
3245 "a closure with signature",
3246 expected_args,
3247 "a closure with signature",
3248 given_args,
3249 );
3250 }
3251 }
3252
3253 fn report_closure_error(
3254 &self,
3255 obligation: &PredicateObligation<'tcx>,
3256 closure_def_id: DefId,
3257 found_kind: ty::ClosureKind,
3258 kind: ty::ClosureKind,
3259 trait_prefix: &'static str,
3260 ) -> Diag<'a> {
3261 let closure_span = self.tcx.def_span(closure_def_id);
3262
3263 let mut err = ClosureKindMismatch {
3264 closure_span,
3265 expected: kind,
3266 found: found_kind,
3267 cause_span: obligation.cause.span,
3268 trait_prefix,
3269 fn_once_label: None,
3270 fn_mut_label: None,
3271 };
3272
3273 if let Some(typeck_results) = &self.typeck_results {
3276 let hir_id = self.tcx.local_def_id_to_hir_id(closure_def_id.expect_local());
3277 match (found_kind, typeck_results.closure_kind_origins().get(hir_id)) {
3278 (ty::ClosureKind::FnOnce, Some((span, place))) => {
3279 err.fn_once_label = Some(ClosureFnOnceLabel {
3280 span: *span,
3281 place: ty::place_to_string_for_capture(self.tcx, place),
3282 trait_prefix,
3283 })
3284 }
3285 (ty::ClosureKind::FnMut, Some((span, place))) => {
3286 err.fn_mut_label = Some(ClosureFnMutLabel {
3287 span: *span,
3288 place: ty::place_to_string_for_capture(self.tcx, place),
3289 trait_prefix,
3290 })
3291 }
3292 _ => {}
3293 }
3294 }
3295
3296 self.dcx().create_err(err)
3297 }
3298
3299 fn report_cyclic_signature_error(
3300 &self,
3301 obligation: &PredicateObligation<'tcx>,
3302 found_trait_ref: ty::TraitRef<'tcx>,
3303 expected_trait_ref: ty::TraitRef<'tcx>,
3304 terr: TypeError<'tcx>,
3305 ) -> Diag<'a> {
3306 let self_ty = found_trait_ref.self_ty();
3307 let (cause, terr) = if let ty::Closure(def_id, _) = *self_ty.kind() {
3308 (
3309 ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
3310 TypeError::CyclicTy(self_ty),
3311 )
3312 } else {
3313 (obligation.cause.clone(), terr)
3314 };
3315 self.report_and_explain_type_error(
3316 TypeTrace::trait_refs(&cause, expected_trait_ref, found_trait_ref),
3317 obligation.param_env,
3318 terr,
3319 )
3320 }
3321
3322 fn report_signature_mismatch_error(
3323 &self,
3324 obligation: &PredicateObligation<'tcx>,
3325 span: Span,
3326 found_trait_ref: ty::TraitRef<'tcx>,
3327 expected_trait_ref: ty::TraitRef<'tcx>,
3328 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3329 let found_trait_ref = self.resolve_vars_if_possible(found_trait_ref);
3330 let expected_trait_ref = self.resolve_vars_if_possible(expected_trait_ref);
3331
3332 expected_trait_ref.self_ty().error_reported()?;
3333 let found_trait_ty = found_trait_ref.self_ty();
3334
3335 let found_did = match *found_trait_ty.kind() {
3336 ty::Closure(did, _) | ty::FnDef(did, _) | ty::Coroutine(did, ..) => Some(did),
3337 _ => None,
3338 };
3339
3340 let found_node = found_did.and_then(|did| self.tcx.hir_get_if_local(did));
3341 let found_span = found_did.and_then(|did| self.tcx.hir_span_if_local(did));
3342
3343 if !self.reported_signature_mismatch.borrow_mut().insert((span, found_span)) {
3344 return Err(self.dcx().span_delayed_bug(span, "already_reported"));
3347 }
3348
3349 let mut not_tupled = false;
3350
3351 let found = match found_trait_ref.args.type_at(1).kind() {
3352 ty::Tuple(tys) => ::alloc::vec::from_elem(ArgKind::empty(), tys.len())vec![ArgKind::empty(); tys.len()],
3353 _ => {
3354 not_tupled = true;
3355 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ArgKind::empty()]))vec![ArgKind::empty()]
3356 }
3357 };
3358
3359 let expected_ty = expected_trait_ref.args.type_at(1);
3360 let expected = match expected_ty.kind() {
3361 ty::Tuple(tys) => {
3362 tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
3363 }
3364 _ => {
3365 not_tupled = true;
3366 ::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())]
3367 }
3368 };
3369
3370 if !self.tcx.is_lang_item(expected_trait_ref.def_id, LangItem::Coroutine) && not_tupled {
3376 return Ok(self.report_and_explain_type_error(
3377 TypeTrace::trait_refs(&obligation.cause, expected_trait_ref, found_trait_ref),
3378 obligation.param_env,
3379 ty::error::TypeError::Mismatch,
3380 ));
3381 }
3382 if found.len() != expected.len() {
3383 let (closure_span, closure_arg_span, found) = found_did
3384 .and_then(|did| {
3385 let node = self.tcx.hir_get_if_local(did)?;
3386 let (found_span, closure_arg_span, found) = self.get_fn_like_arguments(node)?;
3387 Some((Some(found_span), closure_arg_span, found))
3388 })
3389 .unwrap_or((found_span, None, found));
3390
3391 if found.len() != expected.len() {
3397 return Ok(self.report_arg_count_mismatch(
3398 span,
3399 closure_span,
3400 expected,
3401 found,
3402 found_trait_ty.is_closure(),
3403 closure_arg_span,
3404 ));
3405 }
3406 }
3407 Ok(self.report_closure_arg_mismatch(
3408 span,
3409 found_span,
3410 found_trait_ref,
3411 expected_trait_ref,
3412 obligation.cause.code(),
3413 found_node,
3414 obligation.param_env,
3415 ))
3416 }
3417
3418 pub fn get_fn_like_arguments(
3423 &self,
3424 node: Node<'_>,
3425 ) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
3426 let sm = self.tcx.sess.source_map();
3427 Some(match node {
3428 Node::Expr(&hir::Expr {
3429 kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
3430 ..
3431 }) => (
3432 fn_decl_span,
3433 fn_arg_span,
3434 self.tcx
3435 .hir_body(body)
3436 .params
3437 .iter()
3438 .map(|arg| {
3439 if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat
3440 {
3441 Some(ArgKind::Tuple(
3442 Some(span),
3443 args.iter()
3444 .map(|pat| {
3445 sm.span_to_snippet(pat.span)
3446 .ok()
3447 .map(|snippet| (snippet, "_".to_owned()))
3448 })
3449 .collect::<Option<Vec<_>>>()?,
3450 ))
3451 } else {
3452 let name = sm.span_to_snippet(arg.pat.span).ok()?;
3453 Some(ArgKind::Arg(name, "_".to_owned()))
3454 }
3455 })
3456 .collect::<Option<Vec<ArgKind>>>()?,
3457 ),
3458 Node::Item(&hir::Item { kind: hir::ItemKind::Fn { ref sig, .. }, .. })
3459 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
3460 | Node::TraitItem(&hir::TraitItem {
3461 kind: hir::TraitItemKind::Fn(ref sig, _), ..
3462 })
3463 | Node::ForeignItem(&hir::ForeignItem {
3464 kind: hir::ForeignItemKind::Fn(ref sig, _, _),
3465 ..
3466 }) => (
3467 sig.span,
3468 None,
3469 sig.decl
3470 .inputs
3471 .iter()
3472 .map(|arg| match arg.kind {
3473 hir::TyKind::Tup(tys) => ArgKind::Tuple(
3474 Some(arg.span),
3475 ::alloc::vec::from_elem(("_".to_owned(), "_".to_owned()), tys.len())vec![("_".to_owned(), "_".to_owned()); tys.len()],
3476 ),
3477 _ => ArgKind::empty(),
3478 })
3479 .collect::<Vec<ArgKind>>(),
3480 ),
3481 Node::Ctor(variant_data) => {
3482 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| self.tcx.hir_span(id));
3483 (span, None, ::alloc::vec::from_elem(ArgKind::empty(), variant_data.fields().len())vec![ArgKind::empty(); variant_data.fields().len()])
3484 }
3485 _ => {
::core::panicking::panic_fmt(format_args!("non-FnLike node found: {0:?}",
node));
}panic!("non-FnLike node found: {node:?}"),
3486 })
3487 }
3488
3489 pub fn report_arg_count_mismatch(
3493 &self,
3494 span: Span,
3495 found_span: Option<Span>,
3496 expected_args: Vec<ArgKind>,
3497 found_args: Vec<ArgKind>,
3498 is_closure: bool,
3499 closure_arg_span: Option<Span>,
3500 ) -> Diag<'a> {
3501 let kind = if is_closure { "closure" } else { "function" };
3502
3503 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
3504 let arg_length = arguments.len();
3505 let distinct = #[allow(non_exhaustive_omitted_patterns)] match other {
&[ArgKind::Tuple(..)] => true,
_ => false,
}matches!(other, &[ArgKind::Tuple(..)]);
3506 match (arg_length, arguments.get(0)) {
3507 (1, Some(ArgKind::Tuple(_, fields))) => {
3508 ::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())
3509 }
3510 _ => ::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!(
3511 "{} {}argument{}",
3512 arg_length,
3513 if distinct && arg_length > 1 { "distinct " } else { "" },
3514 pluralize!(arg_length)
3515 ),
3516 }
3517 };
3518
3519 let expected_str = args_str(&expected_args, &found_args);
3520 let found_str = args_str(&found_args, &expected_args);
3521
3522 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!(
3523 self.dcx(),
3524 span,
3525 E0593,
3526 "{} is expected to take {}, but it takes {}",
3527 kind,
3528 expected_str,
3529 found_str,
3530 );
3531
3532 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}"));
3533
3534 if let Some(found_span) = found_span {
3535 err.span_label(found_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("takes {0}", found_str))
})format!("takes {found_str}"));
3536
3537 if found_args.is_empty() && is_closure {
3541 let underscores = ::alloc::vec::from_elem("_", expected_args.len())vec!["_"; expected_args.len()].join(", ");
3542 err.span_suggestion_verbose(
3543 closure_arg_span.unwrap_or(found_span),
3544 ::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!(
3545 "consider changing the closure to take and ignore the expected argument{}",
3546 pluralize!(expected_args.len())
3547 ),
3548 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", underscores))
})format!("|{underscores}|"),
3549 Applicability::MachineApplicable,
3550 );
3551 }
3552
3553 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
3554 if fields.len() == expected_args.len() {
3555 let sugg = fields
3556 .iter()
3557 .map(|(name, _)| name.to_owned())
3558 .collect::<Vec<String>>()
3559 .join(", ");
3560 err.span_suggestion_verbose(
3561 found_span,
3562 "change the closure to take multiple arguments instead of a single tuple",
3563 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", sugg))
})format!("|{sugg}|"),
3564 Applicability::MachineApplicable,
3565 );
3566 }
3567 }
3568 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
3569 && fields.len() == found_args.len()
3570 && is_closure
3571 {
3572 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!(
3573 "|({}){}|",
3574 found_args
3575 .iter()
3576 .map(|arg| match arg {
3577 ArgKind::Arg(name, _) => name.to_owned(),
3578 _ => "_".to_owned(),
3579 })
3580 .collect::<Vec<String>>()
3581 .join(", "),
3582 if found_args.iter().any(|arg| match arg {
3584 ArgKind::Arg(_, ty) => ty != "_",
3585 _ => false,
3586 }) {
3587 format!(
3588 ": ({})",
3589 fields
3590 .iter()
3591 .map(|(_, ty)| ty.to_owned())
3592 .collect::<Vec<String>>()
3593 .join(", ")
3594 )
3595 } else {
3596 String::new()
3597 },
3598 );
3599 err.span_suggestion_verbose(
3600 found_span,
3601 "change the closure to accept a tuple instead of individual arguments",
3602 sugg,
3603 Applicability::MachineApplicable,
3604 );
3605 }
3606 }
3607
3608 err
3609 }
3610
3611 pub fn type_implements_fn_trait(
3615 &self,
3616 param_env: ty::ParamEnv<'tcx>,
3617 ty: ty::Binder<'tcx, Ty<'tcx>>,
3618 polarity: ty::PredicatePolarity,
3619 ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
3620 self.commit_if_ok(|_| {
3621 for trait_def_id in [
3622 self.tcx.lang_items().fn_trait(),
3623 self.tcx.lang_items().fn_mut_trait(),
3624 self.tcx.lang_items().fn_once_trait(),
3625 ] {
3626 let Some(trait_def_id) = trait_def_id else { continue };
3627 let var = self.next_ty_var(DUMMY_SP);
3630 let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
3632 let obligation = Obligation::new(
3633 self.tcx,
3634 ObligationCause::dummy(),
3635 param_env,
3636 ty.rebind(ty::TraitPredicate { trait_ref, polarity }),
3637 );
3638 let ocx = ObligationCtxt::new(self);
3639 ocx.register_obligation(obligation);
3640 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
3641 return Ok((
3642 self.tcx
3643 .fn_trait_kind_from_def_id(trait_def_id)
3644 .expect("expected to map DefId to ClosureKind"),
3645 ty.rebind(self.resolve_vars_if_possible(var)),
3646 ));
3647 }
3648 }
3649
3650 Err(())
3651 })
3652 }
3653
3654 fn report_not_const_evaluatable_error(
3655 &self,
3656 obligation: &PredicateObligation<'tcx>,
3657 span: Span,
3658 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3659 if !self.tcx.features().generic_const_exprs()
3660 && !self.tcx.features().min_generic_const_args()
3661 {
3662 let guar = self
3663 .dcx()
3664 .struct_span_err(span, "constant expression depends on a generic parameter")
3665 .with_note("this may fail depending on what value the parameter takes")
3672 .emit();
3673 return Err(guar);
3674 }
3675
3676 match obligation.predicate.kind().skip_binder() {
3677 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => match ct.kind() {
3678 ty::ConstKind::Unevaluated(uv) => {
3679 let mut err =
3680 self.dcx().struct_span_err(span, "unconstrained generic constant");
3681 let const_span = self.tcx.def_span(uv.def);
3682
3683 let const_ty =
3684 self.tcx.type_of(uv.def).instantiate(self.tcx, uv.args).skip_norm_wip();
3685 let cast = if const_ty != self.tcx.types.usize { " as usize" } else { "" };
3686 let msg = "try adding a `where` bound";
3687 match self.tcx.sess.source_map().span_to_snippet(const_span) {
3688 Ok(snippet) => {
3689 let code = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); {0}{1}]:", snippet, cast))
})format!("[(); {snippet}{cast}]:");
3690 let def_id = if let ObligationCauseCode::CompareImplItem {
3691 trait_item_def_id,
3692 ..
3693 } = obligation.cause.code()
3694 {
3695 trait_item_def_id.as_local()
3696 } else {
3697 Some(obligation.cause.body_id)
3698 };
3699 if let Some(def_id) = def_id
3700 && let Some(generics) = self.tcx.hir_get_generics(def_id)
3701 {
3702 err.span_suggestion_verbose(
3703 generics.tail_span_for_predicate_suggestion(),
3704 msg,
3705 ::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()),
3706 Applicability::MaybeIncorrect,
3707 );
3708 } else {
3709 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: where {1}", msg, code))
})format!("{msg}: where {code}"));
3710 };
3711 }
3712 _ => {
3713 err.help(msg);
3714 }
3715 };
3716 Ok(err)
3717 }
3718 ty::ConstKind::Expr(_) => {
3719 let err = self
3720 .dcx()
3721 .struct_span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unconstrained generic constant `{0}`",
ct))
})format!("unconstrained generic constant `{ct}`"));
3722 Ok(err)
3723 }
3724 _ => {
3725 ::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:?}`");
3726 }
3727 },
3728 _ => {
3729 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("unexpected non-ConstEvaluatable predicate, this should not be reachable"))span_bug!(
3730 span,
3731 "unexpected non-ConstEvaluatable predicate, this should not be reachable"
3732 )
3733 }
3734 }
3735 }
3736}