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