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