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