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, ConstKind, GenericArgKind, GenericParamDefKind, TraitRef, Ty, TyCtxt, TypeFoldable,
36 TypeFolder, 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/f5cedb83a788ea9581097abc36a2a8503a7f541c/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/f5cedb83a788ea9581097abc36a2a8503a7f541c/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 if let ConstKind::Param(param_const) = ct.kind() {
876 for param in self
877 .tcx
878 .generics_of(obligation.cause.body_def_id.to_def_id())
879 .own_params
880 .iter()
881 {
882 if let GenericParamDefKind::Const { .. } = param.kind
883 && param.index == param_const.index
884 && param.name == param_const.name
885 {
886 let span = self.tcx.def_span(param.def_id);
887 diag.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` defined here", param.name))
})format!("`{}` defined here", param.name));
888 }
889 }
890 }
891
892 self.note_type_err(
893 &mut diag,
894 &obligation.cause,
895 None,
896 None,
897 TypeError::Sorts(ty::error::ExpectedFound::new(expected_ty, ct_ty)),
898 false,
899 None,
900 );
901 diag
902 }
903 };
904
905 self.note_obligation_cause(&mut err, &obligation);
906 self.silence_redundant_cause(&mut err, &obligation, &root_obligation);
907 err.emit_err()
908 }
909}
910
911impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
912 pub(super) fn apply_do_not_recommend(
913 &self,
914 obligation: &mut PredicateObligation<'tcx>,
915 root_obligation: &PredicateObligation<'tcx>,
916 ) -> bool {
917 let mut base_cause = obligation.cause.code().clone();
918 let mut applied_do_not_recommend = false;
919 loop {
920 if let ObligationCauseCode::ImplDerived(ref c) = base_cause {
921 if self.tcx.do_not_recommend_impl(c.impl_or_alias_def_id) {
922 let code = (*c.derived.parent_code).clone();
923 if code == *root_obligation.cause.code()
926 && root_obligation.cause.span.ctxt() == obligation.cause.span.ctxt()
927 && !root_obligation.cause.span.contains(obligation.cause.span)
928 {
929 obligation.cause.span = root_obligation.cause.span;
930 }
931 obligation.cause.map_code(|_| code);
932 obligation.predicate = c.derived.parent_trait_pred.upcast(self.tcx);
933 applied_do_not_recommend = true;
934 }
935 }
936 if let Some(parent_cause) = base_cause.parent() {
937 base_cause = parent_cause.clone();
938 } else {
939 break;
940 }
941 }
942
943 applied_do_not_recommend
944 }
945
946 fn report_host_effect_error(
947 &self,
948 clause: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>,
949 main_obligation: &PredicateObligation<'tcx>,
950 span: Span,
951 ) -> Diag<'a> {
952 let trait_ref = clause.map_bound(|clause| ty::TraitClause {
956 trait_ref: clause.trait_ref,
957 polarity: ty::ClausePolarity::Positive,
958 });
959 let mut file = None;
960
961 let err_msg = self.get_standard_error_message(
962 trait_ref,
963 Some(clause.constness()),
964 String::new(),
965 &mut file,
966 );
967 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);
968 *diag.long_ty_path() = file;
969 let obligation = Obligation::new(
970 self.tcx,
971 ObligationCause::dummy(),
972 main_obligation.param_env,
973 trait_ref,
974 );
975 if !self.predicate_may_hold(&obligation) {
976 diag.downgrade_to_delayed_bug();
977 }
978
979 if let Ok(Some(ImplSource::UserDefined(impl_data))) =
980 SelectionContext::new(self).poly_select(&obligation.with(self.tcx, trait_ref))
981 {
982 let impl_did = impl_data.impl_def_id;
983 let trait_did = trait_ref.def_id();
984 let impl_span = self.tcx.def_span(impl_did);
985 let trait_name = self.tcx.item_name(trait_did);
986
987 if self.tcx.is_const_trait(trait_did) && !self.tcx.is_const_trait_impl(impl_did) {
988 if !impl_did.is_local() {
989 diag.span_note(
990 impl_span,
991 ::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`"),
992 );
993 }
994
995 if let Some(command) =
996 {
{
'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())
997 .flatten()
998 {
999 let (_, mut format_args) = self.on_unimplemented_components(
1000 trait_ref,
1001 main_obligation,
1002 diag.long_ty_path(),
1003 false,
1004 );
1005 if let ty::Adt(def, args) = trait_ref.self_ty().skip_binder().kind() {
1006 for param in self.tcx.generics_of(def.did()).own_params.iter() {
1007 match param.kind {
1008 GenericParamDefKind::Type { .. }
1009 | GenericParamDefKind::Const { .. } => {
1010 format_args
1011 .generic_args
1012 .push((param.name, args[param.index as usize].to_string()));
1013 }
1014 _ => continue,
1015 }
1016 }
1017 }
1018 let CustomDiagnostic { message, label, notes, parent_label: _ } =
1019 command.eval(None, &format_args);
1020
1021 if let Some(message) = message {
1022 diag.primary_message(message);
1023 }
1024 if let Some(label) = label {
1025 diag.span_label(span, label);
1026 }
1027 for note in notes {
1028 diag.note(note);
1029 }
1030 } else if let Some(impl_did) = impl_did.as_local()
1031 && let item = self.tcx.hir_expect_item(impl_did)
1032 && let hir::ItemKind::Impl(impl_) = item.kind
1033 && impl_.of_trait.is_some()
1034 {
1035 diag.span_suggestion_verbose(
1037 item.span.shrink_to_lo(),
1038 ::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`"),
1039 "const ".to_string(),
1040 Applicability::MaybeIncorrect,
1041 );
1042 }
1043 }
1044 } else if let ty::Param(param) = trait_ref.self_ty().skip_binder().kind()
1045 && let Some(generics) =
1046 self.tcx.hir_node_by_def_id(main_obligation.cause.body_def_id).generics()
1047 {
1048 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!(
1049 "[const] {}",
1050 trait_ref.map_bound(|tr| tr.trait_ref).print_trait_sugared(),
1051 ));
1052 ty::suggest_constraining_type_param(
1053 self.tcx,
1054 generics,
1055 &mut diag,
1056 param.name.as_str(),
1057 &constraint,
1058 Some(trait_ref.def_id()),
1059 None,
1060 );
1061 }
1062 diag
1063 }
1064
1065 fn emit_specialized_closure_kind_error(
1066 &self,
1067 obligation: &PredicateObligation<'tcx>,
1068 mut trait_pred: ty::PolyTraitClause<'tcx>,
1069 ) -> Option<ErrorGuaranteed> {
1070 if self.tcx.is_lang_item(trait_pred.def_id(), LangItem::AsyncFnKindHelper) {
1073 let mut code = obligation.cause.code();
1074 if let ObligationCauseCode::FunctionArg { parent_code, .. } = code {
1076 code = &**parent_code;
1077 }
1078 if let Some((_, Some(parent))) = code.parent_with_predicate() {
1080 trait_pred = parent;
1081 }
1082 }
1083
1084 let original_self_ty = trait_pred.self_ty().skip_binder();
1085 let peeled_self_ty = original_self_ty.peel_refs();
1086
1087 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(..))
1088 && #[allow(non_exhaustive_omitted_patterns)] match peeled_self_ty.kind() {
ty::Closure(..) => true,
_ => false,
}matches!(peeled_self_ty.kind(), ty::Closure(..));
1089
1090 let self_ty = if is_ref_to_closure { peeled_self_ty } else { original_self_ty };
1091
1092 let (expected_kind, is_async) =
1093 if let Some(expected_kind) = self.tcx.fn_trait_kind_from_def_id(trait_pred.def_id()) {
1094 (expected_kind, false)
1095 } else if let Some(expected_kind) =
1096 self.tcx.async_fn_trait_kind_from_def_id(trait_pred.def_id())
1097 {
1098 (expected_kind, true)
1099 } else {
1100 return None;
1101 };
1102 let trait_prefix = if is_async { "Async" } else { "" };
1103
1104 let (closure_def_id, found_args, has_self_borrows) = match *self_ty.kind() {
1105 ty::Closure(def_id, args) => {
1106 (def_id, args.as_closure().sig().map_bound(|sig| sig.inputs()[0]), false)
1107 }
1108 ty::CoroutineClosure(def_id, args) => (
1109 def_id,
1110 args.as_coroutine_closure()
1111 .coroutine_closure_sig()
1112 .map_bound(|sig| sig.tupled_inputs_ty),
1113 !args.as_coroutine_closure().tupled_upvars_ty().is_ty_var()
1114 && args.as_coroutine_closure().has_self_borrows(),
1115 ),
1116 _ => return None,
1117 };
1118
1119 let expected_args = trait_pred.map_bound(|trait_pred| trait_pred.trait_ref.args.type_at(1));
1120
1121 if self.enter_forall(found_args, |found_args| {
1124 self.enter_forall(expected_args, |expected_args| {
1125 !self.can_eq(obligation.param_env, expected_args, found_args)
1126 })
1127 }) {
1128 return None;
1129 }
1130
1131 let mut found_kind = self.closure_kind(self_ty);
1132 let mut kind_origin = None;
1133
1134 if found_kind.is_none()
1135 && is_ref_to_closure
1136 && !is_async
1137 && let Some(local_def_id) = closure_def_id.as_local()
1138 && let Some((inferred_kind, origin)) = (self.infer_closure_kind)(local_def_id)
1139 {
1140 found_kind = Some(inferred_kind);
1141 kind_origin = origin;
1142 }
1143
1144 if let Some(found_kind) = found_kind
1145 && !found_kind.extends(expected_kind)
1146 {
1147 let mut err = self.report_closure_error(
1148 &obligation,
1149 closure_def_id,
1150 found_kind,
1151 expected_kind,
1152 trait_prefix,
1153 kind_origin,
1154 );
1155 self.suggest_change_mut_ref_for_closure(&mut err, &obligation);
1156 self.note_obligation_cause(&mut err, &obligation);
1157 return Some(err.emit_err());
1158 }
1159
1160 if has_self_borrows && expected_kind != ty::ClosureKind::FnOnce {
1164 let coro_kind = match self
1165 .tcx
1166 .coroutine_kind(self.tcx.coroutine_for_closure(closure_def_id))
1167 .unwrap()
1168 {
1169 rustc_hir::CoroutineKind::Desugared(desugaring, _) => desugaring.to_string(),
1170 coro => coro.to_string(),
1171 };
1172 let mut err = self.dcx().create_err(CoroClosureNotFn {
1173 span: self.tcx.def_span(closure_def_id),
1174 kind: expected_kind.as_str(),
1175 coro_kind,
1176 });
1177 self.note_obligation_cause(&mut err, &obligation);
1178 return Some(err.emit_err());
1179 }
1180
1181 None
1182 }
1183
1184 fn fn_arg_obligation(
1185 &self,
1186 obligation: &PredicateObligation<'tcx>,
1187 ) -> Result<(), ErrorGuaranteed> {
1188 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1189 && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
1190 && let arg = arg.peel_borrows()
1191 && let hir::ExprKind::Path(hir::QPath::Resolved(
1192 None,
1193 hir::Path { res: hir::def::Res::Local(hir_id), .. },
1194 )) = arg.kind
1195 && let Node::Pat(pat) = self.tcx.hir_node(*hir_id)
1196 && let Some((preds, guar)) = self.reported_trait_errors.borrow().get(&pat.span)
1197 && preds.contains(&obligation.as_goal())
1198 {
1199 return Err(*guar);
1200 }
1201 Ok(())
1202 }
1203
1204 fn detect_negative_literal(
1205 &self,
1206 obligation: &PredicateObligation<'tcx>,
1207 trait_pred: ty::PolyTraitClause<'tcx>,
1208 err: &mut Diag<'_>,
1209 ) -> bool {
1210 if let ObligationCauseCode::UnOp { hir_id, .. } = obligation.cause.code()
1211 && let hir::Node::Expr(expr) = self.tcx.hir_node(*hir_id)
1212 && let hir::ExprKind::Unary(hir::UnOp::Neg, inner) = expr.kind
1213 && let hir::ExprKind::Lit(lit) = inner.kind
1214 && let LitKind::Int(_, LitIntType::Unsuffixed) = lit.node
1215 {
1216 err.span_suggestion_verbose(
1217 lit.span.shrink_to_hi(),
1218 "consider specifying an integer type that can be negative",
1219 match trait_pred.skip_binder().self_ty().kind() {
1220 ty::Uint(ty::UintTy::Usize) => "isize",
1221 ty::Uint(ty::UintTy::U8) => "i8",
1222 ty::Uint(ty::UintTy::U16) => "i16",
1223 ty::Uint(ty::UintTy::U32) => "i32",
1224 ty::Uint(ty::UintTy::U64) => "i64",
1225 ty::Uint(ty::UintTy::U128) => "i128",
1226 _ => "i64",
1227 }
1228 .to_string(),
1229 Applicability::MaybeIncorrect,
1230 );
1231 return true;
1232 }
1233 false
1234 }
1235
1236 fn try_conversion_context(
1240 &self,
1241 obligation: &PredicateObligation<'tcx>,
1242 trait_pred: ty::PolyTraitClause<'tcx>,
1243 err: &mut Diag<'_>,
1244 ) -> (bool, bool) {
1245 let span = obligation.cause.span;
1246 struct FindMethodSubexprOfTry {
1248 search_span: Span,
1249 }
1250 impl<'v> Visitor<'v> for FindMethodSubexprOfTry {
1251 type Result = ControlFlow<&'v hir::Expr<'v>>;
1252 fn visit_expr(&mut self, ex: &'v hir::Expr<'v>) -> Self::Result {
1253 if let hir::ExprKind::Match(expr, _arms, hir::MatchSource::TryDesugar(_)) = ex.kind
1254 && ex.span.with_lo(ex.span.hi() - BytePos(1)).lo_hi()
1255 == self.search_span.lo_hi()
1256 && let hir::ExprKind::Call(_, [expr, ..]) = expr.kind
1257 {
1258 ControlFlow::Break(expr)
1259 } else {
1260 hir::intravisit::walk_expr(self, ex)
1261 }
1262 }
1263 }
1264 let hir_id = self.tcx.local_def_id_to_hir_id(obligation.cause.body_def_id);
1265 let Some(body_id) = self.tcx.hir_node(hir_id).body_id() else { return (false, false) };
1266 let ControlFlow::Break(expr) =
1267 (FindMethodSubexprOfTry { search_span: span }).visit_body(self.tcx.hir_body(body_id))
1268 else {
1269 return (false, false);
1270 };
1271 let Some(typeck) = &self.typeck_results else {
1272 return (false, false);
1273 };
1274 let ObligationCauseCode::QuestionMark = obligation.cause.code().peel_derives() else {
1275 return (false, false);
1276 };
1277 let self_ty = trait_pred.skip_binder().self_ty();
1278 let found_ty = trait_pred.skip_binder().trait_ref.args.get(1).and_then(|a| a.as_type());
1279 let noted_missing_impl =
1280 self.note_missing_impl_for_question_mark(err, self_ty, found_ty, trait_pred);
1281
1282 let mut prev_ty = self.deeply_resolve_ignoring_regions(
1283 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1284 );
1285
1286 let get_e_type = |prev_ty: Ty<'tcx>| -> Option<Ty<'tcx>> {
1290 let ty::Adt(def, args) = prev_ty.kind() else {
1291 return None;
1292 };
1293 let Some(arg) = args.get(1) else {
1294 return None;
1295 };
1296 if !self.tcx.is_diagnostic_item(sym::Result, def.did()) {
1297 return None;
1298 }
1299 arg.as_type()
1300 };
1301
1302 let mut suggested = false;
1303 let mut chain = ::alloc::vec::Vec::new()vec![];
1304
1305 let mut expr = expr;
1307 while let hir::ExprKind::MethodCall(path_segment, rcvr_expr, args, span) = expr.kind {
1308 expr = rcvr_expr;
1312 chain.push((span, prev_ty));
1313
1314 let next_ty = self.deeply_resolve_ignoring_regions(
1315 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1316 );
1317
1318 let is_diagnostic_item = |symbol: Symbol, ty: Ty<'tcx>| {
1319 let ty::Adt(def, _) = ty.kind() else {
1320 return false;
1321 };
1322 self.tcx.is_diagnostic_item(symbol, def.did())
1323 };
1324 if let Some(ty) = get_e_type(prev_ty)
1328 && let Some(found_ty) = found_ty
1329 && (
1334 ( path_segment.ident.name == sym::map_err
1336 && is_diagnostic_item(sym::Result, next_ty)
1337 ) || ( path_segment.ident.name == sym::ok_or_else
1339 && is_diagnostic_item(sym::Option, next_ty)
1340 )
1341 )
1342 && let ty::Tuple(tys) = found_ty.kind()
1344 && tys.is_empty()
1345 && self.can_eq(obligation.param_env, ty, found_ty)
1347 && let [arg] = args
1349 && let hir::ExprKind::Closure(closure) = arg.kind
1350 && let body = self.tcx.hir_body(closure.body)
1352 && let hir::ExprKind::Block(block, _) = body.value.kind
1353 && let None = block.expr
1354 && let [.., stmt] = block.stmts
1356 && let hir::StmtKind::Semi(expr) = stmt.kind
1357 && let expr_ty = self.deeply_resolve_ignoring_regions(
1358 typeck.expr_ty_adjusted_opt(expr)
1359 .unwrap_or(Ty::new_misc_error(self.tcx)),
1360 )
1361 && self
1362 .infcx
1363 .type_implements_trait(
1364 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1365 [self_ty, expr_ty],
1366 obligation.param_env,
1367 )
1368 .must_apply_modulo_regions()
1369 {
1370 suggested = true;
1371 err.span_suggestion_short(
1372 stmt.span.with_lo(expr.span.hi()),
1373 "remove this semicolon",
1374 String::new(),
1375 Applicability::MachineApplicable,
1376 );
1377 }
1378
1379 prev_ty = next_ty;
1380
1381 if let hir::ExprKind::Path(hir::QPath::Resolved(None, path)) = expr.kind
1382 && let hir::Path { res: hir::def::Res::Local(hir_id), .. } = path
1383 && let hir::Node::Pat(binding) = self.tcx.hir_node(*hir_id)
1384 {
1385 let parent = self.tcx.parent_hir_node(binding.hir_id);
1386 if let hir::Node::LetStmt(local) = parent
1388 && let Some(binding_expr) = local.init
1389 {
1390 expr = binding_expr;
1392 }
1393 if let hir::Node::Param(_param) = parent {
1394 break;
1396 }
1397 }
1398 }
1399 prev_ty = self.deeply_resolve_ignoring_regions(
1403 typeck.expr_ty_adjusted_opt(expr).unwrap_or(Ty::new_misc_error(self.tcx)),
1404 );
1405 chain.push((expr.span, prev_ty));
1406
1407 let mut prev = None;
1408 let mut iter = chain.into_iter().rev().peekable();
1409 while let Some((span, err_ty)) = iter.next() {
1410 let is_last = iter.peek().is_none();
1411 let err_ty = get_e_type(err_ty);
1412 let err_ty = match (err_ty, prev) {
1413 (Some(err_ty), Some(prev)) if !self.can_eq(obligation.param_env, err_ty, prev) => {
1414 err_ty
1415 }
1416 (Some(err_ty), None) => err_ty,
1417 _ => {
1418 prev = err_ty;
1419 continue;
1420 }
1421 };
1422
1423 let implements_from = self
1424 .infcx
1425 .type_implements_trait(
1426 self.tcx.get_diagnostic_item(sym::From).unwrap(),
1427 [self_ty, err_ty],
1428 obligation.param_env,
1429 )
1430 .must_apply_modulo_regions();
1431
1432 let err_ty_str = self.tcx.short_string(err_ty, err.long_ty_path());
1433 let label = if !implements_from && is_last {
1434 ::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!(
1435 "this can't be annotated with `?` because it has type `Result<_, {err_ty_str}>`"
1436 )
1437 } else {
1438 ::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}>`")
1439 };
1440
1441 if !suggested || !implements_from {
1442 err.span_label(span, label);
1443 }
1444 prev = Some(err_ty);
1445 }
1446 (suggested, noted_missing_impl)
1447 }
1448
1449 fn note_missing_impl_for_question_mark(
1450 &self,
1451 err: &mut Diag<'_>,
1452 self_ty: Ty<'_>,
1453 found_ty: Option<Ty<'_>>,
1454 trait_pred: ty::PolyTraitClause<'tcx>,
1455 ) -> bool {
1456 match (self_ty.kind(), found_ty) {
1457 (ty::Adt(def, _), Some(ty))
1458 if let ty::Adt(found, _) = ty.kind()
1459 && def.did().is_local()
1460 && found.did().is_local() =>
1461 {
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 (ty::Adt(def, _), None) if def.did().is_local() => {
1468 let trait_path = self.tcx.short_string(
1469 trait_pred.skip_binder().trait_ref.print_only_trait_path(),
1470 err.long_ty_path(),
1471 );
1472 err.span_note(
1473 self.tcx.def_span(def.did()),
1474 ::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}`"),
1475 );
1476 }
1477 (ty::Adt(def, _), Some(ty)) if def.did().is_local() => {
1478 err.span_note(
1479 self.tcx.def_span(def.did()),
1480 ::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}>`"),
1481 );
1482 }
1483 (_, Some(ty))
1484 if let ty::Adt(def, _) = ty.kind()
1485 && def.did().is_local() =>
1486 {
1487 err.span_note(
1488 self.tcx.def_span(def.did()),
1489 ::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}>`"),
1490 );
1491 }
1492 _ => return false,
1493 }
1494 true
1495 }
1496
1497 fn report_const_param_ty_error(
1498 &self,
1499 ty: Ty<'tcx>,
1500 span: Span,
1501 obligation: &PredicateObligation<'tcx>,
1502 ) -> Diag<'a> {
1503 let mut file = None;
1504 let ty_str = self.tcx.short_string(ty, &mut file);
1505 let mut diag = match ty.kind() {
1506 ty::Float(_) => {
1507 {
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!(
1508 self.dcx(),
1509 span,
1510 E0741,
1511 "`{ty_str}` is forbidden as the type of a const generic parameter",
1512 )
1513 }
1514 ty::FnPtr(..) => {
1515 {
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!(
1516 self.dcx(),
1517 span,
1518 E0741,
1519 "using function pointers as const generic parameters is forbidden",
1520 )
1521 }
1522 ty::RawPtr(_, _) => {
1523 {
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!(
1524 self.dcx(),
1525 span,
1526 E0741,
1527 "using raw pointers as const generic parameters is forbidden",
1528 )
1529 }
1530 ty::Adt(def, _) => {
1531 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!(
1533 self.dcx(),
1534 span,
1535 E0741,
1536 "`{ty_str}` must implement `ConstParamTy` to be used as the type of a const \
1537 generic parameter",
1538 );
1539 if let Some(span) = self.tcx.hir_span_if_local(def.did())
1542 && obligation.cause.code().parent().is_none()
1543 {
1544 if ty.is_structural_eq_shallow(self.tcx) {
1545 diag.span_suggestion_verbose(
1546 span.shrink_to_lo(),
1547 ::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()),
1548 "#[derive(ConstParamTy)]\n",
1549 Applicability::MachineApplicable,
1550 );
1551 } else {
1552 diag.span_suggestion_verbose(
1555 span.shrink_to_lo(),
1556 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {0}",
def.descr()))
})format!(
1557 "add `#[derive(ConstParamTy, PartialEq, Eq)]` to the {}",
1558 def.descr()
1559 ),
1560 "#[derive(ConstParamTy, PartialEq, Eq)]\n",
1561 Applicability::MachineApplicable,
1562 );
1563 }
1564 }
1565 diag
1566 }
1567 _ => {
1568 {
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!(
1569 self.dcx(),
1570 span,
1571 E0741,
1572 "`{ty_str}` can't be used as a const parameter type",
1573 )
1574 }
1575 };
1576 diag.long_ty_path = file;
1577
1578 let mut code = obligation.cause.code();
1579 let mut pred = obligation.predicate.as_trait_clause();
1580 while let Some((next_code, next_pred)) = code.parent_with_predicate() {
1581 if let Some(pred) = pred {
1582 self.enter_forall(pred, |pred| {
1583 let ty = self.tcx.short_string(pred.self_ty(), diag.long_ty_path());
1584 let trait_path = self
1585 .tcx
1586 .short_string(pred.print_modifiers_and_trait_path(), diag.long_ty_path());
1587 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"));
1588 })
1589 }
1590 code = next_code;
1591 pred = next_pred;
1592 }
1593
1594 diag
1595 }
1596}
1597
1598impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
1599 fn can_match_trait(
1600 &self,
1601 param_env: ty::ParamEnv<'tcx>,
1602 goal: ty::TraitClause<'tcx>,
1603 assumption: ty::PolyTraitClause<'tcx>,
1604 ) -> bool {
1605 if goal.polarity != assumption.polarity() {
1607 return false;
1608 }
1609
1610 let trait_assumption = self.instantiate_binder_with_fresh_vars(
1611 DUMMY_SP,
1612 infer::BoundRegionConversionTime::HigherRankedType,
1613 assumption,
1614 );
1615
1616 self.can_eq(param_env, goal.trait_ref, trait_assumption.trait_ref)
1617 }
1618
1619 fn can_match_host_effect(
1620 &self,
1621 param_env: ty::ParamEnv<'tcx>,
1622 goal: ty::HostEffectClause<'tcx>,
1623 assumption: ty::Binder<'tcx, ty::HostEffectClause<'tcx>>,
1624 ) -> bool {
1625 let assumption = self.instantiate_binder_with_fresh_vars(
1626 DUMMY_SP,
1627 infer::BoundRegionConversionTime::HigherRankedType,
1628 assumption,
1629 );
1630
1631 assumption.constness.satisfies(goal.constness)
1632 && self.can_eq(param_env, goal.trait_ref, assumption.trait_ref)
1633 }
1634
1635 fn as_host_effect_clause(
1636 predicate: ty::Predicate<'tcx>,
1637 ) -> Option<ty::Binder<'tcx, ty::HostEffectClause<'tcx>>> {
1638 predicate.as_clause().and_then(|clause| match clause.kind().skip_binder() {
1639 ty::ClauseKind::HostEffect(host_clause) => Some(clause.kind().rebind(host_clause)),
1640 _ => None,
1641 })
1642 }
1643
1644 fn can_match_projection(
1645 &self,
1646 param_env: ty::ParamEnv<'tcx>,
1647 goal: ty::ProjectionClause<'tcx>,
1648 assumption: ty::PolyProjectionClause<'tcx>,
1649 ) -> bool {
1650 let assumption = self.instantiate_binder_with_fresh_vars(
1651 DUMMY_SP,
1652 infer::BoundRegionConversionTime::HigherRankedType,
1653 assumption,
1654 );
1655
1656 self.can_eq(param_env, goal.projection_term, assumption.projection_term)
1657 && self.can_eq(param_env, goal.term, assumption.term)
1658 }
1659
1660 {}
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/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
::tracing_core::__macro_support::Option::Some(1662u32),
::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/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs:1662",
"rustc_trait_selection::error_reporting::traits::fulfillment_errors",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
::tracing_core::__macro_support::Option::Some(1662u32),
::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)]
1663 pub(super) fn error_implies(
1664 &self,
1665 cond: Goal<'tcx, ty::Predicate<'tcx>>,
1666 error: Goal<'tcx, ty::Predicate<'tcx>>,
1667 ) -> bool {
1668 if cond == error {
1669 return true;
1670 }
1671
1672 if cond.param_env != error.param_env {
1676 return false;
1677 }
1678 let param_env = error.param_env;
1679
1680 if let Some(error) = error.predicate.as_trait_clause() {
1681 self.enter_forall(error, |error| {
1682 elaborate(self.tcx, std::iter::once(cond.predicate))
1683 .filter_map(|implied| implied.as_trait_clause())
1684 .any(|implied| self.can_match_trait(param_env, error, implied))
1685 })
1686 } else if let Some(error) = Self::as_host_effect_clause(error.predicate) {
1687 self.enter_forall(error, |error| {
1688 elaborate(self.tcx, std::iter::once(cond.predicate))
1689 .filter_map(Self::as_host_effect_clause)
1690 .any(|implied| self.can_match_host_effect(param_env, error, implied))
1691 })
1692 } else if let Some(error) = error.predicate.as_projection_clause() {
1693 self.enter_forall(error, |error| {
1694 elaborate(self.tcx, std::iter::once(cond.predicate))
1695 .filter_map(|implied| implied.as_projection_clause())
1696 .any(|implied| self.can_match_projection(param_env, error, implied))
1697 })
1698 } else {
1699 false
1700 }
1701 }
1702
1703 pub(super) fn trait_error_implies_projection_error(
1707 &self,
1708 cond: Goal<'tcx, ty::Predicate<'tcx>>,
1709 error: Goal<'tcx, ty::Predicate<'tcx>>,
1710 ) -> bool {
1711 if cond.param_env != error.param_env {
1712 return false;
1713 }
1714 let Some(error) = error.predicate.as_projection_clause() else {
1715 return false;
1716 };
1717
1718 self.enter_forall(error, |error| {
1719 if !error.projection_term.kind.is_trait_projection() {
1720 return false;
1721 }
1722 let trait_pred = ty::TraitClause {
1723 trait_ref: error.projection_term.trait_ref(self.tcx),
1724 polarity: ty::ClausePolarity::Positive,
1725 };
1726 elaborate(self.tcx, std::iter::once(cond.predicate))
1731 .filter_map(|implied| implied.as_trait_clause())
1732 .any(|implied| self.can_match_trait(cond.param_env, trait_pred, implied))
1733 && !self.predicate_must_hold_modulo_regions(&Obligation::new(
1734 self.tcx,
1735 ObligationCause::dummy(),
1736 cond.param_env,
1737 trait_pred,
1738 ))
1739 })
1740 }
1741
1742 {}
#[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/f5cedb83a788ea9581097abc36a2a8503a7f541c/compiler/rustc_trait_selection/src/error_reporting/traits/fulfillment_errors.rs"),
::tracing_core::__macro_support::Option::Some(1742u32),
::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)]
1743 pub(super) fn report_projection_error(
1744 &self,
1745 obligation: &PredicateObligation<'tcx>,
1746 error: &MismatchedProjectionTypes<'tcx>,
1747 ) -> ErrorGuaranteed {
1748 let predicate = self.deeply_resolve_ignoring_regions(obligation.predicate);
1749
1750 if let Err(e) = predicate.error_reported() {
1751 return e;
1752 }
1753
1754 self.probe(|_| {
1755 let bound_predicate = predicate.kind();
1760 let (values, err) = match bound_predicate.skip_binder() {
1761 ty::PredicateKind::Clause(ty::ClauseKind::Projection(data)) => {
1762 let ocx = ObligationCtxt::new(self);
1763
1764 let data = self.instantiate_binder_with_fresh_vars(
1765 obligation.cause.span,
1766 infer::BoundRegionConversionTime::HigherRankedType,
1767 bound_predicate.rebind(data),
1768 );
1769 let unnormalized_term = data.projection_term.to_term(self.tcx, ty::IsRigid::No);
1770 let normalized_term = ocx.normalize(
1771 &obligation.cause,
1772 obligation.param_env,
1773 Unnormalized::new_wip(unnormalized_term),
1774 );
1775
1776 let _ = ocx.try_evaluate_obligations();
1782
1783 if let Err(new_err) =
1784 ocx.eq(&obligation.cause, obligation.param_env, data.term, normalized_term)
1785 {
1786 (
1787 Some((
1788 data.projection_term,
1789 self.deeply_resolve_ignoring_regions(normalized_term),
1790 data.term,
1791 )),
1792 new_err,
1793 )
1794 } else {
1795 (None, error.err)
1796 }
1797 }
1798 _ => (None, error.err),
1799 };
1800
1801 let mut file = None;
1802 let (msg, mut span, mut closure_span) = values
1803 .and_then(|(predicate, normalized_term, expected_term)| {
1804 self.maybe_detailed_projection_msg(
1805 obligation.cause.span,
1806 predicate,
1807 normalized_term,
1808 expected_term,
1809 &mut file,
1810 )
1811 })
1812 .unwrap_or_else(|| {
1813 (
1814 with_forced_trimmed_paths!(format!(
1815 "type mismatch resolving `{}`",
1816 self.tcx.short_string(
1817 self.deeply_resolve_ignoring_regions(predicate),
1818 &mut file
1819 ),
1820 )),
1821 obligation.cause.span,
1822 None,
1823 )
1824 });
1825
1826 if closure_span.is_none()
1830 && let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
1831 && let Node::Expr(arg_expr) = self.tcx.hir_node(*arg_hir_id)
1832 && let hir::ExprKind::Closure(closure) = arg_expr.kind
1833 && closure.kind == hir::ClosureKind::Closure
1834 {
1835 let body = self.tcx.hir_body(closure.body);
1836 let ret_span = match body.value.kind {
1837 hir::ExprKind::Block(hir::Block { expr: Some(expr), .. }, _) => expr.span,
1838 hir::ExprKind::Block(hir::Block { expr: None, stmts: [.., last], .. }, _) => {
1839 last.span
1840 }
1841 _ => body.value.span,
1842 };
1843 if !closure.fn_decl_span.overlaps(ret_span) {
1844 closure_span = Some(closure.fn_decl_span);
1845 span = ret_span;
1846 }
1847 }
1848
1849 let mut diag = struct_span_code_err!(self.dcx(), span, E0271, "{msg}");
1850 *diag.long_ty_path() = file;
1851 let mut mention_bounds = true;
1852 if let Some(span) = closure_span {
1853 if let Some((_, _, expected_ty)) = values
1854 && let Some(expected_ty) = expected_ty.as_type()
1855 && let ty::Closure(def_id, _) = expected_ty.kind()
1856 && self.tcx.def_span(*def_id).overlaps(span)
1857 && let ObligationCauseCode::FunctionArg { parent_code, arg_hir_id, .. } =
1858 obligation.cause.code()
1859 && let ObligationCauseCode::WhereClauseInExpr(def_id, span, _, _)
1860 | ObligationCauseCode::WhereClause(def_id, span) = &**parent_code
1861 {
1862 let mut multispan: MultiSpan = (*span).into();
1867 multispan.push_span_label(*span, "this requires the closure to return itself");
1868 if let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id) {
1869 multispan
1870 .push_span_label(arg.span, "this closure would have to return itself");
1871 }
1872 let in_the_item = match self.tcx.opt_item_name(*def_id) {
1873 Some(name) => format!("in `{name}`"),
1874 None => String::new(),
1875 };
1876 diag.span_note(
1877 multispan,
1878 format!(
1879 "a bound {in_the_item} requires that a closure return itself, which is \
1880 not possible",
1881 ),
1882 );
1883 mention_bounds = false;
1884 } else {
1885 diag.span_label(span, "this closure");
1902 if !span.overlaps(obligation.cause.span) {
1903 diag.span_label(obligation.cause.span, "closure used here");
1905 }
1906 }
1907 }
1908
1909 let secondary_span = self.probe(|_| {
1910 let ty::PredicateKind::Clause(ty::ClauseKind::Projection(proj)) =
1911 predicate.kind().skip_binder()
1912 else {
1913 return None;
1914 };
1915 if !proj.projection_term.kind.is_trait_projection() {
1916 return None;
1917 }
1918
1919 let trait_ref = self.enter_forall_and_leak_universe(
1920 predicate.kind().rebind(proj.projection_term.trait_ref(self.tcx)),
1921 );
1922 let Ok(Some(ImplSource::UserDefined(impl_data))) =
1923 SelectionContext::new(self).select(&obligation.with(self.tcx, trait_ref))
1924 else {
1925 return None;
1926 };
1927
1928 let Ok(node) =
1929 specialization_graph::assoc_def(self.tcx, impl_data.impl_def_id, proj.def_id())
1930 else {
1931 return None;
1932 };
1933
1934 if !node.is_final() {
1935 return None;
1936 }
1937
1938 match self.tcx.hir_get_if_local(node.item.def_id) {
1939 Some(
1940 hir::Node::TraitItem(hir::TraitItem {
1941 kind: hir::TraitItemKind::Type(_, Some(ty)),
1942 ..
1943 })
1944 | hir::Node::ImplItem(hir::ImplItem {
1945 kind: hir::ImplItemKind::Type(ty),
1946 ..
1947 }),
1948 ) => Some((
1949 ty.span.into(),
1950 with_forced_trimmed_paths!(Cow::from(format!(
1951 "type mismatch resolving `{}`",
1952 self.tcx.short_string(
1953 self.deeply_resolve_ignoring_regions(predicate),
1954 diag.long_ty_path()
1955 ),
1956 ))),
1957 true,
1958 )),
1959 _ => None,
1960 }
1961 });
1962
1963 self.note_type_err(
1964 &mut diag,
1965 &obligation.cause,
1966 secondary_span,
1967 values.map(|(_, normalized_ty, expected_ty)| {
1968 obligation.param_env.and(infer::ValuePairs::Terms(ExpectedFound::new(
1969 expected_ty,
1970 normalized_ty,
1971 )))
1972 }),
1973 err,
1974 false,
1975 Some(span),
1976 );
1977 if mention_bounds {
1978 self.note_obligation_cause(&mut diag, obligation);
1979 }
1980 diag.emit_err()
1981 })
1982 }
1983
1984 fn maybe_detailed_projection_msg(
1985 &self,
1986 mut span: Span,
1987 projection_term: ty::AliasTerm<'tcx>,
1988 normalized_ty: ty::Term<'tcx>,
1989 expected_ty: ty::Term<'tcx>,
1990 long_ty_path: &mut Option<PathBuf>,
1991 ) -> Option<(String, Span, Option<Span>)> {
1992 if !projection_term.kind.is_trait_projection() {
1993 return None;
1994 }
1995
1996 let projection_def_id = projection_term.expect_projection_def_id();
1997 let trait_def_id = projection_term.trait_def_id(self.tcx);
1998 let self_ty = projection_term.self_ty();
1999
2000 {
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! {
2001 if self.tcx.is_lang_item(projection_def_id, LangItem::FnOnceOutput) {
2002 let (span, closure_span) = if let ty::Closure(def_id, _) = *self_ty.kind() {
2003 let def_span = self.tcx.def_span(def_id);
2004 if let Some(local_def_id) = def_id.as_local()
2005 && let node = self.tcx.hir_node_by_def_id(local_def_id)
2006 && let Some(fn_decl) = node.fn_decl()
2007 && let Some(id) = node.body_id()
2008 {
2009 span = match fn_decl.output {
2010 hir::FnRetTy::Return(ty) => ty.span,
2011 hir::FnRetTy::DefaultReturn(_) => {
2012 let body = self.tcx.hir_body(id);
2013 match body.value.kind {
2014 hir::ExprKind::Block(
2015 hir::Block { expr: Some(expr), .. },
2016 _,
2017 ) => expr.span,
2018 hir::ExprKind::Block(
2019 hir::Block {
2020 expr: None, stmts: [.., last], ..
2021 },
2022 _,
2023 ) => last.span,
2024 _ => body.value.span,
2025 }
2026 }
2027 };
2028 }
2029 (span, Some(def_span))
2030 } else {
2031 (span, None)
2032 };
2033 let item = match self_ty.kind() {
2034 ty::FnDef(def, _) => self.tcx.item_name(*def).to_string(),
2035 _ => self.tcx.short_string(self_ty, long_ty_path),
2036 };
2037 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
2038 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
2039 Some((format!(
2040 "expected `{item}` to return `{expected_ty}`, but it returns `{normalized_ty}`",
2041 ), span, closure_span))
2042 } else if self.tcx.is_lang_item(trait_def_id, LangItem::Future) {
2043 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
2044 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
2045 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
2046 Some((format!(
2047 "expected `{self_ty}` to be a future that resolves to `{expected_ty}`, but it \
2048 resolves to `{normalized_ty}`"
2049 ), span, None))
2050 } else if Some(trait_def_id) == self.tcx.get_diagnostic_item(sym::Iterator) {
2051 let self_ty = self.tcx.short_string(self_ty, long_ty_path);
2052 let expected_ty = self.tcx.short_string(expected_ty, long_ty_path);
2053 let normalized_ty = self.tcx.short_string(normalized_ty, long_ty_path);
2054 Some((format!(
2055 "expected `{self_ty}` to be an iterator that yields `{expected_ty}`, but it \
2056 yields `{normalized_ty}`"
2057 ), span, None))
2058 } else {
2059 None
2060 }
2061 }
2062 }
2063
2064 pub fn fuzzy_match_tys(
2065 &self,
2066 mut a: Ty<'tcx>,
2067 mut b: Ty<'tcx>,
2068 ignoring_lifetimes: bool,
2069 ) -> Option<CandidateSimilarity> {
2070 fn type_category(tcx: TyCtxt<'_>, t: Ty<'_>) -> Option<u32> {
2073 match t.kind() {
2074 ty::Bool => Some(0),
2075 ty::Char => Some(1),
2076 ty::Str => Some(2),
2077 ty::Adt(def, _) if tcx.is_lang_item(def.did(), LangItem::String) => Some(2),
2078 ty::Int(..)
2079 | ty::Uint(..)
2080 | ty::Float(..)
2081 | ty::Infer(ty::IntVar(..) | ty::FloatVar(..)) => Some(4),
2082 ty::Ref(..) | ty::RawPtr(..) => Some(5),
2083 ty::Array(..) | ty::Slice(..) => Some(6),
2084 ty::FnDef(..) | ty::FnPtr(..) => Some(7),
2085 ty::Dynamic(..) => Some(8),
2086 ty::Closure(..) => Some(9),
2087 ty::Tuple(..) => Some(10),
2088 ty::Param(..) => Some(11),
2089 ty::Alias(_, ty::AliasTy { kind: ty::Projection { .. }, .. }) => Some(12),
2090 ty::Alias(_, ty::AliasTy { kind: ty::Inherent { .. }, .. }) => Some(13),
2091 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. }) => Some(14),
2092 ty::Alias(_, ty::AliasTy { kind: ty::Free { .. }, .. }) => Some(15),
2093 ty::Never => Some(16),
2094 ty::Adt(..) => Some(17),
2095 ty::Coroutine(..) => Some(18),
2096 ty::Foreign(..) => Some(19),
2097 ty::CoroutineWitness(..) => Some(20),
2098 ty::CoroutineClosure(..) => Some(21),
2099 ty::Pat(..) => Some(22),
2100 ty::UnsafeBinder(..) => Some(23),
2101 ty::Placeholder(..) | ty::Bound(..) | ty::Infer(..) | ty::Error(_) => None,
2102 }
2103 }
2104
2105 let strip_references = |mut t: Ty<'tcx>| -> Ty<'tcx> {
2106 loop {
2107 match t.kind() {
2108 ty::Ref(_, inner, _) | ty::RawPtr(inner, _) => t = *inner,
2109 _ => break t,
2110 }
2111 }
2112 };
2113
2114 if !ignoring_lifetimes {
2115 a = strip_references(a);
2116 b = strip_references(b);
2117 }
2118
2119 let cat_a = type_category(self.tcx, a)?;
2120 let cat_b = type_category(self.tcx, b)?;
2121 if a == b {
2122 Some(CandidateSimilarity::Exact { ignoring_lifetimes })
2123 } else if cat_a == cat_b {
2124 match (a.kind(), b.kind()) {
2125 (ty::Adt(def_a, _), ty::Adt(def_b, _)) => def_a == def_b,
2126 (ty::Foreign(def_a), ty::Foreign(def_b)) => def_a == def_b,
2127 (ty::Ref(..) | ty::RawPtr(..), ty::Ref(..) | ty::RawPtr(..)) => {
2133 self.fuzzy_match_tys(a, b, true).is_some()
2134 }
2135 _ => true,
2136 }
2137 .then_some(CandidateSimilarity::Fuzzy { ignoring_lifetimes })
2138 } else if ignoring_lifetimes {
2139 None
2140 } else {
2141 self.fuzzy_match_tys(a, b, true)
2142 }
2143 }
2144
2145 pub(super) fn describe_closure(&self, kind: hir::ClosureKind) -> &'static str {
2146 match kind {
2147 hir::ClosureKind::Closure => "a closure",
2148 hir::ClosureKind::Coroutine(hir::CoroutineKind::Coroutine(_)) => "a coroutine",
2149 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2150 hir::CoroutineDesugaring::Async,
2151 hir::CoroutineSource::Block,
2152 )) => "an async block",
2153 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2154 hir::CoroutineDesugaring::Async,
2155 hir::CoroutineSource::Fn,
2156 )) => "an async function",
2157 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2158 hir::CoroutineDesugaring::Async,
2159 hir::CoroutineSource::Closure,
2160 ))
2161 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Async) => {
2162 "an async closure"
2163 }
2164 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2165 hir::CoroutineDesugaring::AsyncGen,
2166 hir::CoroutineSource::Block,
2167 )) => "an async gen block",
2168 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2169 hir::CoroutineDesugaring::AsyncGen,
2170 hir::CoroutineSource::Fn,
2171 )) => "an async gen function",
2172 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2173 hir::CoroutineDesugaring::AsyncGen,
2174 hir::CoroutineSource::Closure,
2175 ))
2176 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::AsyncGen) => {
2177 "an async gen closure"
2178 }
2179 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2180 hir::CoroutineDesugaring::Gen,
2181 hir::CoroutineSource::Block,
2182 )) => "a gen block",
2183 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2184 hir::CoroutineDesugaring::Gen,
2185 hir::CoroutineSource::Fn,
2186 )) => "a gen function",
2187 hir::ClosureKind::Coroutine(hir::CoroutineKind::Desugared(
2188 hir::CoroutineDesugaring::Gen,
2189 hir::CoroutineSource::Closure,
2190 ))
2191 | hir::ClosureKind::CoroutineClosure(hir::CoroutineDesugaring::Gen) => "a gen closure",
2192 }
2193 }
2194
2195 pub(crate) fn find_similar_impl_candidates(
2196 &self,
2197 trait_def_id: DefId,
2198 self_ty: Ty<'tcx>,
2199 ) -> Vec<ImplCandidate<'tcx>> {
2200 let mut candidates: Vec<_> = self
2201 .tcx
2202 .all_impls(trait_def_id)
2203 .filter_map(|def_id| {
2204 let imp = self.tcx.impl_trait_header(def_id);
2205 if imp.polarity != ty::ImplPolarity::Positive
2206 || !self.tcx.is_user_visible_dep(def_id.krate)
2207 {
2208 return None;
2209 }
2210 let imp = imp.trait_ref.skip_binder();
2211
2212 self.fuzzy_match_tys(self_ty, imp.self_ty(), false).map(|similarity| {
2213 ImplCandidate { trait_ref: imp, similarity, impl_def_id: def_id }
2214 })
2215 })
2216 .collect();
2217 if candidates.iter().any(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. })) {
2218 candidates.retain(|c| #[allow(non_exhaustive_omitted_patterns)] match c.similarity {
CandidateSimilarity::Exact { .. } => true,
_ => false,
}matches!(c.similarity, CandidateSimilarity::Exact { .. }));
2222 }
2223 candidates
2224 }
2225
2226 pub(super) fn report_similar_impl_candidates(
2227 &self,
2228 impl_candidates: &[ImplCandidate<'tcx>],
2229 obligation: &PredicateObligation<'tcx>,
2230 trait_pred: ty::PolyTraitClause<'tcx>,
2231 body_def_id: LocalDefId,
2232 err: &mut Diag<'_>,
2233 other: bool,
2234 param_env: ty::ParamEnv<'tcx>,
2235 ) -> bool {
2236 let parent_map = self.tcx.visible_parent_map(());
2237 let alternative_candidates = |def_id: DefId| {
2238 let mut impl_candidates: Vec<_> = self
2239 .tcx
2240 .all_impls(def_id)
2241 .filter(|def_id| !self.tcx.do_not_recommend_impl(*def_id))
2243 .map(|def_id| (self.tcx.impl_trait_header(def_id), def_id))
2245 .filter_map(|(header, def_id)| {
2246 (header.polarity == ty::ImplPolarity::Positive
2247 || self.tcx.is_automatically_derived(def_id))
2248 .then(|| (header.trait_ref.instantiate_identity().skip_norm_wip(), def_id))
2249 })
2250 .filter(|(trait_ref, _)| {
2251 let self_ty = trait_ref.self_ty();
2252 if let ty::Param(_) = self_ty.kind() {
2254 false
2255 }
2256 else if let ty::Adt(def, _) = self_ty.peel_refs().kind() {
2258 let mut did = def.did();
2262 if self.tcx.visibility(did).is_accessible_from(body_def_id, self.tcx) {
2263 if !did.is_local() {
2265 let mut previously_seen_dids: FxHashSet<DefId> = Default::default();
2266 previously_seen_dids.insert(did);
2267 while let Some(&parent) = parent_map.get(&did)
2268 && let hash_set::Entry::Vacant(v) =
2269 previously_seen_dids.entry(parent)
2270 {
2271 if self.tcx.is_doc_hidden(did) {
2272 return false;
2273 }
2274 v.insert();
2275 did = parent;
2276 }
2277 }
2278 true
2279 } else {
2280 false
2281 }
2282 } else {
2283 true
2284 }
2285 })
2286 .collect();
2287
2288 impl_candidates.sort_by_key(|(tr, _)| tr.to_string());
2289 impl_candidates.dedup();
2290 impl_candidates
2291 };
2292
2293 if let [single] = &impl_candidates
2294 && !self.tcx.do_not_recommend_impl(single.impl_def_id)
2295 {
2296 let self_ty = trait_pred.skip_binder().self_ty();
2297 if !self_ty.has_escaping_bound_vars() {
2298 let self_ty = self.tcx.instantiate_bound_regions_with_erased(trait_pred.self_ty());
2299 if let ty::Ref(_, inner_ty, _) = self_ty.kind()
2300 && self.can_eq(param_env, single.trait_ref.self_ty(), *inner_ty)
2301 && !self.where_clause_expr_matches_failed_self_ty(obligation, self_ty)
2302 {
2303 return true;
2307 }
2308 }
2309
2310 if self.probe(|_| {
2313 let ocx = ObligationCtxt::new(self);
2314
2315 self.enter_forall(trait_pred, |obligation_trait_ref| {
2316 let impl_args = self.fresh_args_for_item(DUMMY_SP, single.impl_def_id);
2317 let impl_trait_ref = ocx.normalize(
2318 &ObligationCause::dummy(),
2319 param_env,
2320 ty::EarlyBinder::bind(self.tcx, single.trait_ref)
2321 .instantiate(self.tcx, impl_args),
2322 );
2323
2324 ocx.register_obligations(
2325 self.tcx
2326 .clauses_of(single.impl_def_id)
2327 .instantiate(self.tcx, impl_args)
2328 .into_iter()
2329 .map(|(clause, _)| {
2330 Obligation::new(
2331 self.tcx,
2332 ObligationCause::dummy(),
2333 param_env,
2334 clause.skip_norm_wip(),
2335 )
2336 }),
2337 );
2338 if !ocx.try_evaluate_obligations().no_errors() {
2339 return false;
2340 }
2341
2342 let mut terrs = ::alloc::vec::Vec::new()vec![];
2343 for (obligation_arg, impl_arg) in
2344 std::iter::zip(obligation_trait_ref.trait_ref.args, impl_trait_ref.args)
2345 {
2346 if (obligation_arg, impl_arg).references_error() {
2347 return false;
2348 }
2349 if let Err(terr) =
2350 ocx.eq(&ObligationCause::dummy(), param_env, impl_arg, obligation_arg)
2351 {
2352 terrs.push(terr);
2353 }
2354 if !ocx.try_evaluate_obligations().no_errors() {
2355 return false;
2356 }
2357 }
2358
2359 if terrs.len() == impl_trait_ref.args.len() {
2361 return false;
2362 }
2363
2364 let impl_trait_ref = self.deeply_resolve_ignoring_regions(impl_trait_ref);
2365 if impl_trait_ref.references_error() {
2366 return false;
2367 }
2368
2369 if let [child, ..] = &err.children[..]
2370 && child.level == Sublevel::Help
2371 && let Some(line) = child.messages.get(0)
2372 && let Some(line) = line.0.as_str()
2373 && line.starts_with("the trait")
2374 && line.contains("is not implemented for")
2375 {
2376 err.children.remove(0);
2383 }
2384
2385 let traits = self.cmp_traits(
2386 obligation_trait_ref.def_id(),
2387 &obligation_trait_ref.trait_ref.args.as_slice()[1..],
2388 impl_trait_ref.def_id,
2389 &impl_trait_ref.args.as_slice()[1..],
2390 );
2391 let traits_content = (traits.0.content(), traits.1.content());
2392 let types = self.cmp(obligation_trait_ref.self_ty(), impl_trait_ref.self_ty());
2393 let types_content = (types.0.content(), types.1.content());
2394 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 `")];
2395 if traits_content.0 == traits_content.1 {
2396 msg.push(StringPart::normal(
2397 impl_trait_ref.print_trait_sugared().to_string(),
2398 ));
2399 } else {
2400 msg.extend(traits.0.0);
2401 }
2402 msg.extend([
2403 StringPart::normal("` "),
2404 StringPart::highlighted("is not"),
2405 StringPart::normal(" implemented for `"),
2406 ]);
2407 if types_content.0 == types_content.1 {
2408 let ty = self
2409 .tcx
2410 .short_string(obligation_trait_ref.self_ty(), err.long_ty_path());
2411 msg.push(StringPart::normal(ty));
2412 } else {
2413 msg.extend(types.0.0);
2414 }
2415 msg.push(StringPart::normal("`"));
2416 if types_content.0 == types_content.1 {
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 it"),
2423 ]);
2424 } else if traits_content.0 == traits_content.1 {
2425 msg.extend([
2426 StringPart::normal("\nbut it "),
2427 StringPart::highlighted("is"),
2428 StringPart::normal(" implemented for `"),
2429 ]);
2430 msg.extend(types.1.0);
2431 msg.push(StringPart::normal("`"));
2432 } else {
2433 msg.push(StringPart::normal("\nbut trait `"));
2434 msg.extend(traits.1.0);
2435 msg.extend([
2436 StringPart::normal("` "),
2437 StringPart::highlighted("is"),
2438 StringPart::normal(" implemented for `"),
2439 ]);
2440 msg.extend(types.1.0);
2441 msg.push(StringPart::normal("`"));
2442 }
2443 err.highlighted_span_help(self.tcx.def_span(single.impl_def_id), msg);
2444
2445 if let [TypeError::Sorts(exp_found)] = &terrs[..] {
2446 let exp_found = self.deeply_resolve_ignoring_regions(*exp_found);
2447 let expected =
2448 self.tcx.short_string(exp_found.expected, err.long_ty_path());
2449 let found = self.tcx.short_string(exp_found.found, err.long_ty_path());
2450 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![
2451 StringPart::normal("for that trait implementation, "),
2452 StringPart::normal("expected `"),
2453 StringPart::highlighted(expected),
2454 StringPart::normal("`, found `"),
2455 StringPart::highlighted(found),
2456 StringPart::normal("`"),
2457 ]);
2458 self.suggest_function_pointers_impl(None, &exp_found, err);
2459 }
2460
2461 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2462 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2463 && !crates.is_empty()
2464 {
2465 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2466 err.help("you can use `cargo tree` to explore your dependency tree");
2467 }
2468 true
2469 })
2470 }) {
2471 return true;
2472 }
2473 }
2474
2475 let other = if other { "other " } else { "" };
2476 let report = |mut candidates: Vec<(TraitRef<'tcx>, DefId)>, err: &mut Diag<'_>| {
2477 candidates.retain(|(tr, _)| !tr.references_error());
2478 if candidates.is_empty() {
2479 return false;
2480 }
2481 let mut specific_candidates = candidates.clone();
2482 specific_candidates.retain(|(tr, _)| {
2483 tr.with_replaced_self_ty(self.tcx, trait_pred.skip_binder().self_ty())
2484 == trait_pred.skip_binder().trait_ref
2485 });
2486 if !specific_candidates.is_empty() {
2487 candidates = specific_candidates;
2490 }
2491 if let &[(cand, def_id)] = &candidates[..] {
2492 if self.tcx.is_diagnostic_item(sym::FromResidual, cand.def_id)
2493 && !self.tcx.features().enabled(sym::try_trait_v2)
2494 {
2495 return false;
2496 }
2497 let mut multi_span = MultiSpan::from_span(self.tcx.def_span(def_id));
2498 let (desc, mention_castable) =
2499 match (cand.self_ty().kind(), trait_pred.self_ty().skip_binder().kind()) {
2500 (ty::FnPtr(..), ty::FnDef(..)) => {
2501 (" implemented for fn pointer `", ", cast using `as`")
2502 }
2503 (ty::FnPtr(..), _) => (" implemented for fn pointer `", ""),
2504 _ => {
2505 let evaluate_obligations = || {
2506 let ocx = ObligationCtxt::new_with_diagnostics(self);
2507 self.enter_forall(trait_pred, |obligation_trait_ref| {
2508 let impl_args = self.fresh_args_for_item(DUMMY_SP, def_id);
2509 let impl_trait_ref = ocx.normalize(
2510 &ObligationCause::dummy(),
2511 param_env,
2512 ty::EarlyBinder::bind(self.tcx, cand)
2513 .instantiate(self.tcx, impl_args),
2514 );
2515 if ocx
2516 .eq(
2517 &ObligationCause::dummy(),
2518 param_env,
2519 obligation_trait_ref.trait_ref,
2520 impl_trait_ref,
2521 )
2522 .is_err()
2523 {
2524 return TraitErrors::NoErrors;
2525 }
2526 ocx.register_obligations(
2527 self.tcx
2528 .clauses_of(def_id)
2529 .instantiate(self.tcx, impl_args)
2530 .into_iter()
2531 .map(|(clause, span)| {
2532 Obligation::new(
2533 self.tcx,
2534 ObligationCause::dummy_with_span(span),
2535 param_env,
2536 clause.skip_normalization(),
2537 )
2538 }),
2539 );
2540 ocx.try_evaluate_obligations()
2541 })
2542 };
2543 let failing_obligations =
2544 if !self.tcx.clauses_of(def_id).clauses.is_empty() {
2545 self.probe(|_| evaluate_obligations())
2546 } else {
2547 TraitErrors::NoErrors
2548 };
2549
2550 if failing_obligations.no_errors() {
2551 (" implemented for `", "")
2552 } else {
2553 for error in failing_obligations {
2554 multi_span.push_span_label(
2555 error.root_obligation.cause.span,
2556 ::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!(
2557 "unsatisfied requirement introduced here: `{}`",
2558 self.tcx.short_string(
2559 error.root_obligation.predicate,
2560 err.long_ty_path()
2561 ),
2562 ),
2563 );
2564 }
2565
2566 (" conditionally implemented for `", "")
2567 }
2568 }
2569 };
2570 let trait_ = self.tcx.short_string(cand.print_trait_sugared(), err.long_ty_path());
2571 let self_ty = self.tcx.short_string(cand.self_ty(), err.long_ty_path());
2572 err.highlighted_span_help(
2573 multi_span,
2574 ::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![
2575 StringPart::normal(format!("the trait `{trait_}` ")),
2576 StringPart::highlighted("is"),
2577 StringPart::normal(desc),
2578 StringPart::highlighted(self_ty),
2579 StringPart::normal("`"),
2580 StringPart::normal(mention_castable),
2581 ],
2582 );
2583 return true;
2584 }
2585 let trait_ref = TraitRef::identity(self.tcx, candidates[0].0.def_id);
2586 let mut traits: Vec<_> =
2588 candidates.iter().map(|(c, _)| c.print_only_trait_path().to_string()).collect();
2589 traits.sort();
2590 traits.dedup();
2591 let all_traits_equal = traits.len() == 1;
2594 let mut types: Vec<_> =
2595 candidates.iter().map(|(c, _)| c.self_ty().to_string()).collect();
2596 types.sort();
2597 types.dedup();
2598 let all_types_equal = types.len() == 1;
2599
2600 let end = if candidates.len() <= 9 || self.tcx.sess.opts.verbose {
2601 candidates.len()
2602 } else {
2603 8
2604 };
2605 if candidates.len() < 5 {
2606 let spans: Vec<_> =
2607 candidates.iter().map(|&(_, def_id)| self.tcx.def_span(def_id)).collect();
2608 let mut span: MultiSpan = spans.into();
2609 for (c, def_id) in &candidates {
2610 let msg = if all_traits_equal {
2611 ::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()))
2612 } else if all_types_equal {
2613 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}`",
self.tcx.short_string(c.print_only_trait_path(),
err.long_ty_path())))
})format!(
2614 "`{}`",
2615 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path())
2616 )
2617 } else {
2618 ::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!(
2619 "`{}` implements `{}`",
2620 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2621 self.tcx.short_string(c.print_only_trait_path(), err.long_ty_path()),
2622 )
2623 };
2624 span.push_span_label(self.tcx.def_span(*def_id), msg);
2625 }
2626 let msg = if all_types_equal {
2627 ::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!(
2628 "`{}` implements trait `{}`",
2629 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2630 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2631 )
2632 } else {
2633 ::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!(
2634 "the following {other}types implement trait `{}`",
2635 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2636 )
2637 };
2638 err.span_help(span, msg);
2639 } else {
2640 let mut tuple_min_arity = usize::MAX;
2646 let mut tuple_max_arity = 0_usize;
2647 let mut last_arity = None;
2648 let mut all_types_tuples_cont_arity = true;
2649 candidates.sort_by(|(c1, _), (c2, _)| {
2650 if let ty::Tuple(tys1) = c1.self_ty().kind()
2651 && let ty::Tuple(tys2) = c2.self_ty().kind()
2652 {
2653 tys1.len().cmp(&tys2.len())
2654 } else {
2655 std::cmp::Ordering::Equal
2656 }
2657 });
2658 let candidate_names: Vec<String> = candidates
2659 .iter()
2660 .map(|(c, _)| {
2661 if all_traits_equal {
2662 if all_types_tuples_cont_arity
2663 && let ty::Tuple(tys) = c.self_ty().kind()
2664 && last_arity.map_or(1, |a: usize| a.abs_diff(tys.len())) == 1
2665 {
2666 last_arity = Some(tys.len());
2667 if tys.len() > tuple_max_arity {
2668 tuple_max_arity = tys.len();
2669 }
2670 if tys.len() < tuple_min_arity {
2671 tuple_min_arity = tys.len();
2672 }
2673 } else {
2674 all_types_tuples_cont_arity = false;
2675 }
2676 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("\n {0}",
self.tcx.short_string(c.self_ty(), err.long_ty_path())))
})format!(
2677 "\n {}",
2678 self.tcx.short_string(c.self_ty(), err.long_ty_path())
2679 )
2680 } else if all_types_equal {
2681 ::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!(
2682 "\n {}",
2683 self.tcx
2684 .short_string(c.print_only_trait_path(), err.long_ty_path())
2685 )
2686 } else {
2687 ::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!(
2688 "\n `{}` implements `{}`",
2689 self.tcx.short_string(c.self_ty(), err.long_ty_path()),
2690 self.tcx
2691 .short_string(c.print_only_trait_path(), err.long_ty_path()),
2692 )
2693 }
2694 })
2695 .collect();
2696
2697 let details = if all_traits_equal && all_types_tuples_cont_arity {
2698 if tuple_min_arity == 0 {
2699 ::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}")
2700 } else {
2701 ::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!(
2702 "for tuples of arity {tuple_min_arity} up to and including {tuple_max_arity}"
2703 )
2704 }
2705 } else {
2706 String::new()
2707 };
2708 let (candidate_names, end) = if all_traits_equal && all_types_tuples_cont_arity {
2709 (
2710 ::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![
2711 format!("\n (T\u{2081}, T\u{2082}, …, T\u{2099}) {details}"),
2713 ],
2714 1,
2715 )
2716 } else {
2717 (candidate_names, end)
2718 };
2719 let msg = if all_types_equal {
2720 ::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!(
2721 "`{}` implements trait `{}`",
2722 self.tcx.short_string(candidates[0].0.self_ty(), err.long_ty_path()),
2723 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2724 )
2725 } else {
2726 ::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!(
2727 "the following {other}types implement trait `{}`",
2728 self.tcx.short_string(trait_ref.print_trait_sugared(), err.long_ty_path()),
2729 )
2730 };
2731
2732 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!(
2733 "{msg}:{}{}",
2734 candidate_names[..end].join(""),
2735 if candidates.len() > 9 && !self.tcx.sess.opts.verbose {
2736 format!("\nand {} others", candidates.len() - 8)
2737 } else {
2738 String::new()
2739 }
2740 ));
2741 }
2742
2743 if let ty::Adt(def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2744 && let crates = self.tcx.duplicate_crate_names(def.did().krate)
2745 && !crates.is_empty()
2746 {
2747 self.note_two_crate_versions(def.did().krate, MultiSpan::new(), err);
2748 err.help("you can use `cargo tree` to explore your dependency tree");
2749 }
2750 true
2751 };
2752
2753 let impl_candidates = impl_candidates
2756 .into_iter()
2757 .cloned()
2758 .filter(|cand| !self.tcx.do_not_recommend_impl(cand.impl_def_id))
2759 .collect::<Vec<_>>();
2760
2761 let def_id = trait_pred.def_id();
2762 if impl_candidates.is_empty() {
2763 if self.tcx.trait_is_auto(def_id)
2764 || self.tcx.lang_items().iter().any(|(_, id)| id == def_id)
2765 || self.tcx.get_diagnostic_name(def_id).is_some()
2766 {
2767 return false;
2769 }
2770 return report(alternative_candidates(def_id), err);
2771 }
2772
2773 let mut impl_candidates: Vec<_> = impl_candidates
2780 .iter()
2781 .cloned()
2782 .filter(|cand| !cand.trait_ref.references_error())
2783 .map(|mut cand| {
2784 cand.trait_ref = self
2788 .tcx
2789 .try_normalize_erasing_regions(
2790 ty::TypingEnv::non_body_analysis(self.tcx, cand.impl_def_id),
2791 Unnormalized::new_wip(cand.trait_ref),
2792 )
2793 .unwrap_or(cand.trait_ref);
2794 cand
2795 })
2796 .collect();
2797 impl_candidates.sort_by_key(|cand| {
2798 let len = if let GenericArgKind::Type(ty) = cand.trait_ref.args[0].kind()
2800 && let ty::Array(_, len) = ty.kind()
2801 {
2802 len.try_to_target_usize(self.tcx).unwrap_or(u64::MAX)
2804 } else {
2805 0
2806 };
2807
2808 (cand.similarity, len, cand.trait_ref.to_string())
2809 });
2810 let mut impl_candidates: Vec<_> =
2811 impl_candidates.into_iter().map(|cand| (cand.trait_ref, cand.impl_def_id)).collect();
2812 impl_candidates.dedup();
2813
2814 report(impl_candidates, err)
2815 }
2816
2817 fn report_similar_impl_candidates_for_root_obligation(
2818 &self,
2819 obligation: &PredicateObligation<'tcx>,
2820 trait_predicate: ty::Binder<'tcx, ty::TraitClause<'tcx>>,
2821 body_def_id: LocalDefId,
2822 err: &mut Diag<'_>,
2823 ) {
2824 let mut code = obligation.cause.code();
2831 let mut trait_pred = trait_predicate;
2832 let mut peeled = false;
2833 while let Some((parent_code, parent_trait_pred)) = code.parent_with_predicate() {
2834 code = parent_code;
2835 if let Some(parent_trait_pred) = parent_trait_pred {
2836 trait_pred = parent_trait_pred;
2837 peeled = true;
2838 }
2839 }
2840 let def_id = trait_pred.def_id();
2841 if peeled && !self.tcx.trait_is_auto(def_id) && self.tcx.as_lang_item(def_id).is_none() {
2847 let impl_candidates = self.find_similar_impl_candidates(
2848 trait_pred.def_id(),
2849 trait_pred.self_ty().skip_binder(),
2850 );
2851 self.report_similar_impl_candidates(
2852 &impl_candidates,
2853 obligation,
2854 trait_pred,
2855 body_def_id,
2856 err,
2857 true,
2858 obligation.param_env,
2859 );
2860 }
2861 }
2862
2863 fn get_parent_trait_ref(
2865 &self,
2866 code: &ObligationCauseCode<'tcx>,
2867 ) -> Option<(Ty<'tcx>, Option<Span>)> {
2868 match code {
2869 ObligationCauseCode::BuiltinDerived(data) => {
2870 let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
2871 match self.get_parent_trait_ref(&data.parent_code) {
2872 Some(t) => Some(t),
2873 None => {
2874 let ty = parent_trait_ref.skip_binder().self_ty();
2875 let span = TyCategory::from_ty(self.tcx, ty)
2876 .map(|(_, def_id)| self.tcx.def_span(def_id));
2877 Some((ty, span))
2878 }
2879 }
2880 }
2881 ObligationCauseCode::FunctionArg { parent_code, .. } => {
2882 self.get_parent_trait_ref(parent_code)
2883 }
2884 _ => None,
2885 }
2886 }
2887
2888 fn check_same_trait_different_version(
2889 &self,
2890 err: &mut Diag<'_>,
2891 trait_pred: ty::PolyTraitClause<'tcx>,
2892 ) -> bool {
2893 let get_trait_impls = |trait_def_id| {
2894 let mut trait_impls = ::alloc::vec::Vec::new()vec![];
2895 self.tcx.for_each_relevant_impl(
2896 trait_def_id,
2897 trait_pred.skip_binder().self_ty(),
2898 |impl_def_id| {
2899 let impl_trait_header = self.tcx.impl_trait_header(impl_def_id);
2900 trait_impls
2901 .push(self.tcx.def_span(impl_trait_header.trait_ref.skip_binder().def_id));
2902 },
2903 );
2904 trait_impls
2905 };
2906 self.check_same_definition_different_crate(
2907 err,
2908 trait_pred.def_id(),
2909 self.tcx.visible_traits(),
2910 get_trait_impls,
2911 "trait",
2912 )
2913 }
2914
2915 pub fn note_two_crate_versions(
2916 &self,
2917 krate: CrateNum,
2918 sp: impl Into<MultiSpan>,
2919 err: &mut Diag<'_>,
2920 ) {
2921 let crate_name = self.tcx.crate_name(krate);
2922 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!(
2923 "there are multiple different versions of crate `{crate_name}` in the dependency graph"
2924 );
2925 err.span_note(sp, crate_msg);
2926 }
2927
2928 fn note_adt_version_mismatch(&self, err: &mut Diag<'_>, trait_pred: ty::PolyTraitClause<'tcx>) {
2929 let ty::Adt(impl_self_def, _) = trait_pred.self_ty().skip_binder().peel_refs().kind()
2930 else {
2931 return;
2932 };
2933
2934 let impl_self_did = impl_self_def.did();
2935
2936 if impl_self_did.krate == LOCAL_CRATE {
2939 return;
2940 }
2941
2942 let impl_self_path = self.comparable_path(impl_self_did);
2943 let impl_self_crate_name = self.tcx.crate_name(impl_self_did.krate);
2944 let similar_items: UnordSet<_> = self
2945 .tcx
2946 .visible_parent_map(())
2947 .items()
2948 .filter_map(|(&item, _)| {
2949 if impl_self_did == item {
2951 return None;
2952 }
2953 if item.krate == LOCAL_CRATE {
2956 return None;
2957 }
2958 if impl_self_crate_name != self.tcx.crate_name(item.krate) {
2961 return None;
2962 }
2963 if !self.tcx.def_kind(item).is_adt() {
2966 return None;
2967 }
2968 let path = self.comparable_path(item);
2969 let is_similar = path.ends_with(&impl_self_path) || impl_self_path.ends_with(&path);
2972 is_similar.then_some((item, path))
2973 })
2974 .collect();
2975
2976 let mut similar_items =
2977 similar_items.into_items().into_sorted_stable_ord_by_key(|(_, path)| path);
2978 similar_items.dedup();
2979
2980 for (similar_item, _) in similar_items {
2981 err.span_help(self.tcx.def_span(similar_item), "item with same name found");
2982 self.note_two_crate_versions(similar_item.krate, MultiSpan::new(), err);
2983 }
2984 }
2985
2986 fn check_same_name_different_path(
2987 &self,
2988 err: &mut Diag<'_>,
2989 obligation: &PredicateObligation<'tcx>,
2990 trait_pred: ty::PolyTraitClause<'tcx>,
2991 ) -> bool {
2992 let mut suggested = false;
2993 let trait_def_id = trait_pred.def_id();
2994 let trait_has_same_params = |other_trait_def_id: DefId| -> bool {
2995 let trait_generics = self.tcx.generics_of(trait_def_id);
2996 let other_trait_generics = self.tcx.generics_of(other_trait_def_id);
2997
2998 if trait_generics.count() != other_trait_generics.count() {
2999 return false;
3000 }
3001 trait_generics.own_params.iter().zip(other_trait_generics.own_params.iter()).all(
3002 |(a, b)| match (&a.kind, &b.kind) {
3003 (ty::GenericParamDefKind::Lifetime, ty::GenericParamDefKind::Lifetime)
3004 | (
3005 ty::GenericParamDefKind::Type { .. },
3006 ty::GenericParamDefKind::Type { .. },
3007 )
3008 | (
3009 ty::GenericParamDefKind::Const { .. },
3010 ty::GenericParamDefKind::Const { .. },
3011 ) => true,
3012 _ => false,
3013 },
3014 )
3015 };
3016 let trait_name = self.tcx.item_name(trait_def_id);
3017 if let Some(other_trait_def_id) = self.tcx.all_traits_including_private().find(|&def_id| {
3018 trait_def_id != def_id
3019 && trait_name == self.tcx.item_name(def_id)
3020 && trait_has_same_params(def_id)
3021 && !self.tcx.is_lang_item(def_id, LangItem::PointeeSized)
3023 && self.predicate_must_hold_modulo_regions(&Obligation::new(
3024 self.tcx,
3025 obligation.cause.clone(),
3026 obligation.param_env,
3027 trait_pred.map_bound(|tr| ty::TraitClause {
3028 trait_ref: ty::TraitRef::new(self.tcx, def_id, tr.trait_ref.args),
3029 ..tr
3030 }),
3031 ))
3032 }) {
3033 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!(
3034 "`{}` implements similarly named trait `{}`, but not `{}`",
3035 trait_pred.self_ty(),
3036 self.tcx.def_path_str(other_trait_def_id),
3037 trait_pred.print_modifiers_and_trait_path()
3038 ));
3039 suggested = true;
3040 }
3041 suggested
3042 }
3043
3044 pub fn note_different_trait_with_same_name(
3049 &self,
3050 err: &mut Diag<'_>,
3051 obligation: &PredicateObligation<'tcx>,
3052 trait_pred: ty::PolyTraitClause<'tcx>,
3053 ) -> bool {
3054 if self.check_same_trait_different_version(err, trait_pred) {
3055 return true;
3056 }
3057 self.check_same_name_different_path(err, obligation, trait_pred)
3058 }
3059
3060 fn comparable_path(&self, did: DefId) -> String {
3063 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("::{0}",
self.tcx.def_path_str(did)))
})format!("::{}", self.tcx.def_path_str(did))
3064 }
3065
3066 pub(super) fn mk_trait_obligation_with_new_self_ty(
3071 &self,
3072 param_env: ty::ParamEnv<'tcx>,
3073 trait_ref_and_ty: ty::Binder<'tcx, (ty::TraitClause<'tcx>, Ty<'tcx>)>,
3074 ) -> PredicateObligation<'tcx> {
3075 let trait_pred = trait_ref_and_ty
3076 .map_bound(|(tr, new_self_ty)| tr.with_replaced_self_ty(self.tcx, new_self_ty));
3077
3078 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, trait_pred)
3079 }
3080
3081 fn predicate_can_apply(
3084 &self,
3085 param_env: ty::ParamEnv<'tcx>,
3086 pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>> + TypeFoldable<TyCtxt<'tcx>>,
3087 ) -> bool {
3088 struct ParamToVarFolder<'a, 'tcx> {
3089 infcx: &'a InferCtxt<'tcx>,
3090 var_map: FxHashMap<Ty<'tcx>, Ty<'tcx>>,
3091 }
3092
3093 impl<'a, 'tcx> TypeFolder<TyCtxt<'tcx>> for ParamToVarFolder<'a, 'tcx> {
3094 fn cx(&self) -> TyCtxt<'tcx> {
3095 self.infcx.tcx
3096 }
3097
3098 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
3102 match ty.kind() {
3103 ty::Param(_) => {
3104 let infcx = self.infcx;
3105 *self.var_map.entry(ty).or_insert_with(|| infcx.next_ty_var(DUMMY_SP))
3106 }
3107 &ty::Alias(is_rigid, alias)
3111 if is_rigid == ty::IsRigid::Yes
3112 && ty.has_type_flags(ty::TypeFlags::HAS_TY_PARAM) =>
3113 {
3114 let alias = alias.fold_with(self);
3115 Ty::new_alias(self.cx(), ty::IsRigid::No, alias)
3116 }
3117 _ => ty.super_fold_with(self),
3118 }
3119 }
3120 }
3121
3122 self.probe(|_| {
3123 let cleaned_pred =
3124 pred.fold_with(&mut ParamToVarFolder { infcx: self, var_map: Default::default() });
3125
3126 let InferOk { value: cleaned_pred, .. } = self
3127 .infcx
3128 .at(&ObligationCause::dummy(), param_env)
3129 .normalize(Unnormalized::new_wip(cleaned_pred));
3130
3131 let obligation =
3132 Obligation::new(self.tcx, ObligationCause::dummy(), param_env, cleaned_pred);
3133
3134 self.predicate_may_hold(&obligation)
3135 })
3136 }
3137
3138 fn suggest_change_mut_ref_for_closure(
3139 &self,
3140 err: &mut Diag<'_>,
3141 obligation: &PredicateObligation<'tcx>,
3142 ) {
3143 if let ObligationCauseCode::FunctionArg { arg_hir_id, .. } = obligation.cause.code()
3144 && let (_, Some(root_trait_pred)) =
3145 obligation.cause.code().peel_derives_with_predicate()
3146 && let Node::Expr(arg) = self.tcx.hir_node(*arg_hir_id)
3147 && let hir::ExprKind::AddrOf(hir::BorrowKind::Ref, hir::Mutability::Not, _) = arg.kind
3148 {
3149 let mut obligation = obligation.clone();
3150 obligation.cause.span = arg.span;
3153 self.suggest_change_mut(&obligation, err, root_trait_pred);
3154 }
3155 }
3156
3157 fn silence_redundant_cause(
3161 &self,
3162 err: &mut Diag<'_>,
3163 obligation: &PredicateObligation<'tcx>,
3164 root_obligation: &PredicateObligation<'tcx>,
3165 ) {
3166 let hir_id = match root_obligation.cause.code() {
3167 ObligationCauseCode::WellFormed(WellFormedLoc::HirId(hir_id))
3168 | ObligationCauseCode::VariableType(hir_id)
3169 | ObligationCauseCode::WhereClauseInExpr(_, _, hir_id, _)
3170 | ObligationCauseCode::SizedCallReturnType(hir_id) => *hir_id,
3171 ObligationCauseCode::WellFormed(WellFormedLoc::Param { function, .. }) => {
3172 self.tcx.local_def_id_to_hir_id(*function)
3173 }
3174 _ => return,
3175 };
3176
3177 let pred = self.tcx.erase_and_anonymize_regions(obligation.predicate);
3179
3180 if let Some(preds) = self.reported_hir_errors.borrow().get(&hir_id)
3182 && preds.contains(&pred)
3183 {
3184 err.downgrade_to_delayed_bug();
3185 } else {
3186 self.reported_hir_errors.borrow_mut().entry(hir_id).or_default().insert(pred);
3187 }
3188
3189 for (_, node) in self.tcx.hir_parent_iter(hir_id) {
3192 let hir_id = match node {
3193 hir::Node::LetStmt(stmt) => stmt.hir_id,
3194 hir::Node::Stmt(stmt) => stmt.hir_id,
3195 hir::Node::Crate(_)
3196 | hir::Node::Item(_)
3197 | hir::Node::ImplItem(_)
3198 | hir::Node::TraitItem(_) => break,
3199 _ => continue,
3200 };
3201 if let Some(preds) = self.reported_hir_errors.borrow().get(&hir_id)
3202 && preds.contains(&pred)
3203 {
3204 err.downgrade_to_delayed_bug();
3205 } else {
3206 self.reported_hir_errors.borrow_mut().entry(hir_id).or_default().insert(pred);
3207 }
3208 break;
3209 }
3210 }
3211
3212 pub fn note_obligation_cause(
3213 &self,
3214 err: &mut Diag<'_>,
3215 obligation: &PredicateObligation<'tcx>,
3216 ) {
3217 if !self.maybe_note_obligation_cause_for_async_await(err, obligation) {
3220 self.note_obligation_cause_code(
3221 obligation.cause.body_def_id,
3222 err,
3223 obligation.predicate,
3224 obligation.param_env,
3225 obligation.cause.code(),
3226 &mut ::alloc::vec::Vec::new()vec![],
3227 &mut Default::default(),
3228 );
3229 self.suggest_swapping_lhs_and_rhs(
3230 err,
3231 obligation.predicate,
3232 obligation.param_env,
3233 obligation.cause.code(),
3234 );
3235 self.suggest_borrow_for_unsized_closure_return(
3236 obligation.cause.body_def_id,
3237 err,
3238 obligation.predicate,
3239 );
3240 self.suggest_unsized_bound_if_applicable(err, obligation);
3241 if let Some(span) = err.span.primary_span()
3242 && self
3243 .tcx
3244 .resolutions(())
3245 .paths_matching_assoc_types
3246 .contains(&span.with_parent(None))
3247 {
3248 err.subdiagnostic(AssocTypeWithSameName { span: span.shrink_to_lo() });
3249 }
3250 }
3251 }
3252
3253 pub(super) fn is_recursive_obligation(
3254 &self,
3255 obligated_types: &mut Vec<Ty<'tcx>>,
3256 cause_code: &ObligationCauseCode<'tcx>,
3257 ) -> bool {
3258 if let ObligationCauseCode::BuiltinDerived(data) = cause_code {
3259 let parent_trait_ref = self.deeply_resolve_ignoring_regions(data.parent_trait_pred);
3260 let self_ty = parent_trait_ref.skip_binder().self_ty();
3261 if obligated_types.iter().any(|ot| ot == &self_ty) {
3262 return true;
3263 }
3264 if let ty::Adt(def, args) = self_ty.kind()
3265 && let [arg] = &args.as_slice()
3266 && let ty::GenericArgKind::Type(ty) = arg.kind()
3267 && let ty::Adt(inner_def, _) = ty.kind()
3268 && inner_def == def
3269 {
3270 return true;
3271 }
3272 }
3273 false
3274 }
3275
3276 fn get_standard_error_message(
3277 &self,
3278 trait_predicate: ty::PolyTraitClause<'tcx>,
3279 predicate_constness: Option<ty::BoundConstness>,
3280 post_message: String,
3281 long_ty_path: &mut Option<PathBuf>,
3282 ) -> String {
3283 ::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!(
3284 "the trait bound `{}` is not satisfied{post_message}",
3285 self.tcx.short_string(
3286 trait_predicate.print_with_bound_constness(predicate_constness),
3287 long_ty_path,
3288 ),
3289 )
3290 }
3291
3292 fn select_transmute_obligation_for_reporting(
3293 &self,
3294 obligation: &PredicateObligation<'tcx>,
3295 trait_predicate: ty::PolyTraitClause<'tcx>,
3296 root_obligation: &PredicateObligation<'tcx>,
3297 ) -> (PredicateObligation<'tcx>, ty::PolyTraitClause<'tcx>) {
3298 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
3299 return (obligation.clone(), trait_predicate);
3300 }
3301
3302 let ocx = ObligationCtxt::new(self);
3303 let normalized_predicate = self.tcx.erase_and_anonymize_regions(
3304 self.tcx.instantiate_bound_regions_with_erased(trait_predicate),
3305 );
3306 let trait_ref = normalized_predicate.trait_ref;
3307
3308 let assume = ocx.normalize(
3309 &obligation.cause,
3310 obligation.param_env,
3311 Unnormalized::new_wip(trait_ref.args.const_at(2)),
3312 );
3313
3314 let Some(assume) = rustc_transmute::Assume::from_const(self.tcx, assume) else {
3315 return (obligation.clone(), trait_predicate);
3316 };
3317
3318 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!(
3319 rustc_transmute::TransmuteTypeEnv::new(self.tcx).is_transmutable(
3320 trait_ref.args.type_at(1),
3321 trait_ref.args.type_at(0),
3322 assume,
3323 ),
3324 Answer::Yes,
3325 );
3326
3327 if is_normalized_yes
3329 && let ty::PredicateKind::Clause(ty::ClauseKind::Trait(root_pred)) =
3330 root_obligation.predicate.kind().skip_binder()
3331 && root_pred.def_id() == trait_predicate.def_id()
3332 {
3333 return (root_obligation.clone(), root_obligation.predicate.kind().rebind(root_pred));
3334 }
3335
3336 (obligation.clone(), trait_predicate)
3337 }
3338
3339 fn get_safe_transmute_error_and_reason(
3340 &self,
3341 obligation: PredicateObligation<'tcx>,
3342 trait_pred: ty::PolyTraitClause<'tcx>,
3343 span: Span,
3344 ) -> GetSafeTransmuteErrorAndReason {
3345 self.probe(|_| {
3346 if obligation.predicate.has_non_region_param() || obligation.has_non_region_infer() {
3349 return GetSafeTransmuteErrorAndReason::Default;
3350 }
3351
3352 let trait_pred = self.tcx.erase_and_anonymize_regions(
3354 self.tcx.instantiate_bound_regions_with_erased(trait_pred),
3355 );
3356
3357 let ocx = ObligationCtxt::new(self);
3358 let assume = ocx.normalize(
3359 &obligation.cause,
3360 obligation.param_env,
3361 Unnormalized::new_wip(trait_pred.trait_ref.args.const_at(2)),
3362 );
3363
3364 let Some(assume) = rustc_transmute::Assume::from_const(self.infcx.tcx, assume) else {
3365 self.dcx().span_delayed_bug(
3366 span,
3367 "Unable to construct rustc_transmute::Assume where it was previously possible",
3368 );
3369 return GetSafeTransmuteErrorAndReason::Silent;
3370 };
3371
3372 let dst = trait_pred.trait_ref.args.type_at(0);
3373 let src = trait_pred.trait_ref.args.type_at(1);
3374 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}`");
3375
3376 match rustc_transmute::TransmuteTypeEnv::new(self.infcx.tcx)
3377 .is_transmutable(src, dst, assume)
3378 {
3379 Answer::No(reason) => {
3380 let safe_transmute_explanation = match reason {
3381 Reason::SrcIsNotYetSupported => {
3382 ::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")
3383 }
3384 Reason::DstIsNotYetSupported => {
3385 ::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")
3386 }
3387 Reason::DstIsBitIncompatible => {
3388 ::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!(
3389 "at least one value of `{src}` isn't a bit-valid value of `{dst}`"
3390 )
3391 }
3392 Reason::DstUninhabited => {
3393 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is uninhabited", dst))
})format!("`{dst}` is uninhabited")
3394 }
3395 Reason::DstMayHaveSafetyInvariants => {
3396 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` may carry safety invariants",
dst))
})format!("`{dst}` may carry safety invariants")
3397 }
3398 Reason::DstIsTooBig => {
3399 ::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}`")
3400 }
3401 Reason::DstRefIsTooBig { src, src_size, dst, dst_size } => {
3402 ::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!(
3403 "the size of `{src}` ({src_size} bytes) \
3404 is smaller than that of `{dst}` ({dst_size} bytes)"
3405 )
3406 }
3407 Reason::SrcSizeOverflow => {
3408 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
src))
})format!(
3409 "values of the type `{src}` are too big for the target architecture"
3410 )
3411 }
3412 Reason::DstSizeOverflow => {
3413 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("values of the type `{0}` are too big for the target architecture",
dst))
})format!(
3414 "values of the type `{dst}` are too big for the target architecture"
3415 )
3416 }
3417 Reason::DstHasStricterAlignment { src_min_align, dst_min_align } => {
3418 ::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!(
3419 "the minimum alignment of `{src}` ({src_min_align}) should be \
3420 greater than that of `{dst}` ({dst_min_align})"
3421 )
3422 }
3423 Reason::DstIsMoreUnique => {
3424 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` is a shared reference, but `{1}` is a unique reference",
src, dst))
})format!(
3425 "`{src}` is a shared reference, but `{dst}` is a unique reference"
3426 )
3427 }
3428 Reason::TypeError => {
3430 return GetSafeTransmuteErrorAndReason::Silent;
3431 }
3432 Reason::SrcLayoutUnknown => {
3433 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", src))
})format!("`{src}` has an unknown layout")
3434 }
3435 Reason::DstLayoutUnknown => {
3436 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` has an unknown layout", dst))
})format!("`{dst}` has an unknown layout")
3437 }
3438 };
3439 GetSafeTransmuteErrorAndReason::Error {
3440 err_msg,
3441 safe_transmute_explanation: Some(safe_transmute_explanation),
3442 }
3443 }
3444 Answer::Yes => ::rustc_span::macros::bug_impl(Some(span),
format_args!("Inconsistent rustc_transmute::is_transmutable(...) result, got Yes"),
Location::caller())span_bug!(
3446 span,
3447 "Inconsistent rustc_transmute::is_transmutable(...) result, got Yes",
3448 ),
3449 Answer::If(_) => GetSafeTransmuteErrorAndReason::Error {
3454 err_msg,
3455 safe_transmute_explanation: None,
3456 },
3457 }
3458 })
3459 }
3460
3461 fn find_explicit_cast_type(
3464 &self,
3465 param_env: ty::ParamEnv<'tcx>,
3466 found_ty: Ty<'tcx>,
3467 self_ty: Ty<'tcx>,
3468 ) -> Option<Ty<'tcx>> {
3469 let ty::Ref(region, inner_ty, mutbl) = *found_ty.kind() else {
3470 return None;
3471 };
3472
3473 let mut derefs = (self.autoderef_steps)(inner_ty).into_iter();
3474 derefs.next(); let deref_target = derefs.into_iter().next()?.0;
3476
3477 let cast_ty = Ty::new_ref(self.tcx, region, deref_target, mutbl);
3478
3479 let Some(from_def_id) = self.tcx.get_diagnostic_item(sym::From) else {
3480 return None;
3481 };
3482 let Some(try_from_def_id) = self.tcx.get_diagnostic_item(sym::TryFrom) else {
3483 return None;
3484 };
3485
3486 if self.has_impl_for_type(
3487 param_env,
3488 ty::TraitRef::new(
3489 self.tcx,
3490 from_def_id,
3491 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3492 ),
3493 ) {
3494 Some(cast_ty)
3495 } else if self.has_impl_for_type(
3496 param_env,
3497 ty::TraitRef::new(
3498 self.tcx,
3499 try_from_def_id,
3500 self.tcx.mk_args(&[self_ty.into(), cast_ty.into()]),
3501 ),
3502 ) {
3503 Some(cast_ty)
3504 } else {
3505 None
3506 }
3507 }
3508
3509 fn has_impl_for_type(
3510 &self,
3511 param_env: ty::ParamEnv<'tcx>,
3512 trait_ref: ty::TraitRef<'tcx>,
3513 ) -> bool {
3514 let obligation = Obligation::new(
3515 self.tcx,
3516 ObligationCause::dummy(),
3517 param_env,
3518 ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Positive },
3519 );
3520
3521 self.predicate_must_hold_modulo_regions(&obligation)
3522 }
3523
3524 fn add_tuple_trait_message(
3525 &self,
3526 obligation_cause_code: &ObligationCauseCode<'tcx>,
3527 err: &mut Diag<'_>,
3528 ) {
3529 match obligation_cause_code {
3530 ObligationCauseCode::RustCall => {
3531 err.primary_message("functions with the \"rust-call\" ABI must take a single non-self tuple argument");
3532 }
3533 ObligationCauseCode::WhereClause(def_id, _) if self.tcx.is_fn_trait(*def_id) => {
3534 err.code(E0059);
3535 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!(
3536 "type parameter to bare `{}` trait must be a tuple",
3537 self.tcx.def_path_str(*def_id)
3538 ));
3539 }
3540 _ => {}
3541 }
3542 }
3543
3544 fn try_to_add_help_message(
3545 &self,
3546 root_obligation: &PredicateObligation<'tcx>,
3547 obligation: &PredicateObligation<'tcx>,
3548 trait_predicate: ty::PolyTraitClause<'tcx>,
3549 err: &mut Diag<'_>,
3550 span: Span,
3551 is_fn_trait: bool,
3552 suggested: bool,
3553 ) {
3554 let body_def_id = obligation.cause.body_def_id;
3555 let span = if let ObligationCauseCode::BinOp { rhs_span, .. } = obligation.cause.code() {
3556 *rhs_span
3557 } else {
3558 span
3559 };
3560
3561 let trait_def_id = trait_predicate.def_id();
3563 if is_fn_trait
3564 && let Ok((implemented_kind, params)) = self.type_implements_fn_trait(
3565 obligation.param_env,
3566 trait_predicate.self_ty(),
3567 trait_predicate.skip_binder().polarity,
3568 )
3569 {
3570 self.add_help_message_for_fn_trait(trait_predicate, err, implemented_kind, params);
3571 } else if !trait_predicate.has_non_region_infer()
3572 && self.predicate_can_apply(obligation.param_env, trait_predicate)
3573 {
3574 self.suggest_restricting_param_bound(
3582 err,
3583 trait_predicate,
3584 None,
3585 obligation.cause.body_def_id,
3586 );
3587 } else if trait_def_id.is_local()
3588 && self.tcx.trait_impls_of(trait_def_id).is_empty()
3589 && !self.tcx.trait_is_auto(trait_def_id)
3590 && !self.tcx.trait_is_alias(trait_def_id)
3591 && trait_predicate.polarity() == ty::ClausePolarity::Positive
3592 {
3593 err.span_help(
3594 self.tcx.def_span(trait_def_id),
3595 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"),
3596 );
3597 } else if !suggested && trait_predicate.polarity() == ty::ClausePolarity::Positive {
3598 let impl_candidates = self.find_similar_impl_candidates(
3600 trait_predicate.def_id(),
3601 trait_predicate.self_ty().skip_binder(),
3602 );
3603 if !self.report_similar_impl_candidates(
3604 &impl_candidates,
3605 obligation,
3606 trait_predicate,
3607 body_def_id,
3608 err,
3609 true,
3610 obligation.param_env,
3611 ) {
3612 self.report_similar_impl_candidates_for_root_obligation(
3613 obligation,
3614 trait_predicate,
3615 body_def_id,
3616 err,
3617 );
3618 }
3619
3620 self.suggest_convert_to_slice(
3621 err,
3622 obligation,
3623 trait_predicate,
3624 impl_candidates.as_slice(),
3625 span,
3626 );
3627
3628 self.suggest_tuple_wrapping(err, root_obligation, obligation);
3629 }
3630 self.suggest_shadowed_inherent_method(err, obligation, trait_predicate);
3631 }
3632
3633 fn add_help_message_for_fn_trait(
3634 &self,
3635 trait_pred: ty::PolyTraitClause<'tcx>,
3636 err: &mut Diag<'_>,
3637 implemented_kind: ty::ClosureKind,
3638 params: ty::Binder<'tcx, Ty<'tcx>>,
3639 ) {
3640 let selected_kind = self
3647 .tcx
3648 .fn_trait_kind_from_def_id(trait_pred.def_id())
3649 .expect("expected to map DefId to ClosureKind");
3650 if !implemented_kind.extends(selected_kind) {
3651 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!(
3652 "`{}` implements `{}`, but it must implement `{}`, which is more general",
3653 trait_pred.skip_binder().self_ty(),
3654 implemented_kind,
3655 selected_kind
3656 ));
3657 }
3658
3659 let ty::Tuple(given) = *params.skip_binder().kind() else {
3661 return;
3662 };
3663
3664 let expected_ty = trait_pred.skip_binder().trait_ref.args.type_at(1);
3665 let ty::Tuple(expected) = *expected_ty.kind() else {
3666 return;
3667 };
3668
3669 if expected.len() != given.len() {
3670 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!(
3672 "expected a closure taking {} argument{}, but one taking {} argument{} was given",
3673 given.len(),
3674 pluralize!(given.len()),
3675 expected.len(),
3676 pluralize!(expected.len()),
3677 ));
3678 return;
3679 }
3680
3681 let given_ty = Ty::new_fn_ptr(
3682 self.tcx,
3683 params.rebind(self.tcx.mk_fn_sig_safe_rust_abi(given, self.tcx.types.unit)),
3684 );
3685 let expected_ty = Ty::new_fn_ptr(
3686 self.tcx,
3687 trait_pred.rebind(self.tcx.mk_fn_sig_safe_rust_abi(expected, self.tcx.types.unit)),
3688 );
3689
3690 if !self.same_type_modulo_infer(given_ty, expected_ty) {
3691 let (expected_args, given_args) = self.cmp(expected_ty, given_ty);
3693 err.note_expected_found(
3694 "type with signature",
3695 expected_args,
3696 &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} with signature",
trait_pred.self_ty().skip_binder().prefix_string(self.tcx)))
})format!(
3697 "{} with signature",
3698 trait_pred.self_ty().skip_binder().prefix_string(self.tcx)
3699 ),
3700 given_args,
3701 );
3702 }
3703 }
3704
3705 fn report_closure_error(
3706 &self,
3707 obligation: &PredicateObligation<'tcx>,
3708 closure_def_id: DefId,
3709 found_kind: ty::ClosureKind,
3710 kind: ty::ClosureKind,
3711 trait_prefix: &'static str,
3712 kind_origin: Option<(Span, rustc_middle::hir::place::Place<'tcx>)>,
3713 ) -> Diag<'a> {
3714 let closure_span = self.tcx.def_span(closure_def_id);
3715
3716 let mut err = ClosureKindMismatch {
3717 closure_span,
3718 expected: kind,
3719 found: found_kind,
3720 cause_span: obligation.cause.span,
3721 trait_prefix,
3722 fn_once_label: None,
3723 fn_mut_label: None,
3724 };
3725
3726 let origin = kind_origin.or_else(|| {
3729 let typeck_results = self.typeck_results.as_ref()?;
3730 let local_def_id = closure_def_id.as_local()?;
3731 let hir_id = self.tcx.local_def_id_to_hir_id(local_def_id);
3732 typeck_results.closure_kind_origins().get(hir_id).cloned()
3733 });
3734
3735 match (found_kind, origin) {
3736 (ty::ClosureKind::FnOnce, Some((span, place))) => {
3737 err.fn_once_label = Some(ClosureFnOnceLabel {
3738 span,
3739 place: ty::place_to_string_for_capture(self.tcx, &place),
3740 trait_prefix,
3741 })
3742 }
3743 (ty::ClosureKind::FnMut, Some((span, place))) => {
3744 err.fn_mut_label = Some(ClosureFnMutLabel {
3745 span,
3746 place: ty::place_to_string_for_capture(self.tcx, &place),
3747 trait_prefix,
3748 })
3749 }
3750 _ => {}
3751 }
3752 self.dcx().create_err(err)
3753 }
3754
3755 fn report_cyclic_signature_error(
3756 &self,
3757 obligation: &PredicateObligation<'tcx>,
3758 found_trait_ref: ty::TraitRef<'tcx>,
3759 expected_trait_ref: ty::TraitRef<'tcx>,
3760 terr: TypeError<'tcx>,
3761 ) -> Diag<'a> {
3762 let self_ty = found_trait_ref.self_ty();
3763 let (cause, terr) = if let ty::Closure(def_id, _) = *self_ty.kind() {
3764 (
3765 ObligationCause::dummy_with_span(self.tcx.def_span(def_id)),
3766 TypeError::CyclicTy(self_ty),
3767 )
3768 } else {
3769 (obligation.cause.clone(), terr)
3770 };
3771 self.report_and_explain_type_error(
3772 TypeTrace::trait_refs(&cause, expected_trait_ref, found_trait_ref),
3773 obligation.param_env,
3774 terr,
3775 )
3776 }
3777
3778 fn report_signature_mismatch_error(
3779 &self,
3780 obligation: &PredicateObligation<'tcx>,
3781 span: Span,
3782 found_trait_ref: ty::TraitRef<'tcx>,
3783 expected_trait_ref: ty::TraitRef<'tcx>,
3784 ) -> Result<Diag<'a>, ErrorGuaranteed> {
3785 let found_trait_ref = self.deeply_resolve_ignoring_regions(found_trait_ref);
3786 let expected_trait_ref = self.deeply_resolve_ignoring_regions(expected_trait_ref);
3787
3788 expected_trait_ref.self_ty().error_reported()?;
3789 let found_trait_ty = found_trait_ref.self_ty();
3790
3791 let found_did = match *found_trait_ty.kind() {
3792 ty::Closure(did, _) | ty::FnDef(did, _) | ty::Coroutine(did, ..) => Some(did),
3793 _ => None,
3794 };
3795
3796 let found_node = found_did.and_then(|did| self.tcx.hir_get_if_local(did));
3797 let found_span = found_did.and_then(|did| self.tcx.hir_span_if_local(did));
3798
3799 if !self.reported_signature_mismatch.borrow_mut().insert((span, found_span)) {
3800 return Err(self.dcx().span_delayed_bug(span, "already_reported"));
3803 }
3804
3805 let mut not_tupled = false;
3806
3807 let found = match found_trait_ref.args.type_at(1).kind() {
3808 ty::Tuple(tys) => ::alloc::vec::from_elem_global(ArgKind::empty(), tys.len())vec![ArgKind::empty(); tys.len()],
3809 _ => {
3810 not_tupled = true;
3811 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ArgKind::empty()]))vec![ArgKind::empty()]
3812 }
3813 };
3814
3815 let expected_ty = expected_trait_ref.args.type_at(1);
3816 let expected = match expected_ty.kind() {
3817 ty::Tuple(tys) => {
3818 tys.iter().map(|t| ArgKind::from_expected_ty(t, Some(span))).collect()
3819 }
3820 _ => {
3821 not_tupled = true;
3822 ::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())]
3823 }
3824 };
3825
3826 if !self.tcx.is_lang_item(expected_trait_ref.def_id, LangItem::Coroutine) && not_tupled {
3832 return Ok(self.report_and_explain_type_error(
3833 TypeTrace::trait_refs(&obligation.cause, expected_trait_ref, found_trait_ref),
3834 obligation.param_env,
3835 ty::error::TypeError::Mismatch,
3836 ));
3837 }
3838 if found.len() != expected.len() {
3839 let (closure_span, closure_arg_span, found) = found_did
3840 .and_then(|did| {
3841 let node = self.tcx.hir_get_if_local(did)?;
3842 let (found_span, closure_arg_span, found) = self.get_fn_like_arguments(node)?;
3843 Some((Some(found_span), closure_arg_span, found))
3844 })
3845 .unwrap_or((found_span, None, found));
3846
3847 if found.len() != expected.len() {
3853 return Ok(self.report_arg_count_mismatch(
3854 span,
3855 closure_span,
3856 expected,
3857 found,
3858 found_trait_ty.is_closure(),
3859 closure_arg_span,
3860 ));
3861 }
3862 }
3863 Ok(self.report_closure_arg_mismatch(
3864 span,
3865 found_span,
3866 found_trait_ref,
3867 expected_trait_ref,
3868 obligation.cause.code(),
3869 found_node,
3870 obligation.param_env,
3871 ))
3872 }
3873
3874 pub fn get_fn_like_arguments(
3879 &self,
3880 node: Node<'_>,
3881 ) -> Option<(Span, Option<Span>, Vec<ArgKind>)> {
3882 let sm = self.tcx.sess.source_map();
3883 Some(match node {
3884 Node::Expr(&hir::Expr {
3885 kind: hir::ExprKind::Closure(&hir::Closure { body, fn_decl_span, fn_arg_span, .. }),
3886 ..
3887 }) => (
3888 fn_decl_span,
3889 fn_arg_span,
3890 self.tcx
3891 .hir_body(body)
3892 .params
3893 .iter()
3894 .map(|arg| {
3895 if let hir::Pat { kind: hir::PatKind::Tuple(args, _), span, .. } = *arg.pat
3896 {
3897 Some(ArgKind::Tuple(
3898 Some(span),
3899 args.iter()
3900 .map(|pat| {
3901 sm.span_to_snippet(pat.span)
3902 .ok()
3903 .map(|snippet| (snippet, "_".to_owned()))
3904 })
3905 .collect::<Option<Vec<_>>>()?,
3906 ))
3907 } else {
3908 let name = sm.span_to_snippet(arg.pat.span).ok()?;
3909 Some(ArgKind::Arg(name, "_".to_owned()))
3910 }
3911 })
3912 .collect::<Option<Vec<ArgKind>>>()?,
3913 ),
3914 Node::Item(&hir::Item { kind: hir::ItemKind::Fn { ref sig, .. }, .. })
3915 | Node::ImplItem(&hir::ImplItem { kind: hir::ImplItemKind::Fn(ref sig, _), .. })
3916 | Node::TraitItem(&hir::TraitItem {
3917 kind: hir::TraitItemKind::Fn(ref sig, _), ..
3918 })
3919 | Node::ForeignItem(&hir::ForeignItem {
3920 kind: hir::ForeignItemKind::Fn(ref sig, _, _),
3921 ..
3922 }) => (
3923 sig.span,
3924 None,
3925 sig.decl
3926 .inputs
3927 .iter()
3928 .map(|arg| match arg.kind {
3929 hir::TyKind::Tup(tys) => ArgKind::Tuple(
3930 Some(arg.span),
3931 ::alloc::vec::from_elem_global(("_".to_owned(), "_".to_owned()), tys.len())vec![("_".to_owned(), "_".to_owned()); tys.len()],
3932 ),
3933 _ => ArgKind::empty(),
3934 })
3935 .collect::<Vec<ArgKind>>(),
3936 ),
3937 Node::Ctor(variant_data) => {
3938 let span = variant_data.ctor_hir_id().map_or(DUMMY_SP, |id| self.tcx.hir_span(id));
3939 (span, None, ::alloc::vec::from_elem_global(ArgKind::empty(), variant_data.fields().len())vec![ArgKind::empty(); variant_data.fields().len()])
3940 }
3941 _ => {
::core::panicking::panic_fmt(format_args!("non-FnLike node found: {0:?}",
node));
}panic!("non-FnLike node found: {node:?}"),
3942 })
3943 }
3944
3945 pub fn report_arg_count_mismatch(
3949 &self,
3950 span: Span,
3951 found_span: Option<Span>,
3952 expected_args: Vec<ArgKind>,
3953 found_args: Vec<ArgKind>,
3954 is_closure: bool,
3955 closure_arg_span: Option<Span>,
3956 ) -> Diag<'a> {
3957 let kind = if is_closure { "closure" } else { "function" };
3958
3959 let args_str = |arguments: &[ArgKind], other: &[ArgKind]| {
3960 let arg_length = arguments.len();
3961 let distinct = #[allow(non_exhaustive_omitted_patterns)] match other {
&[ArgKind::Tuple(..)] => true,
_ => false,
}matches!(other, &[ArgKind::Tuple(..)]);
3962 match (arg_length, arguments.get(0)) {
3963 (1, Some(ArgKind::Tuple(_, fields))) => {
3964 ::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())
3965 }
3966 _ => ::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!(
3967 "{} {}argument{}",
3968 arg_length,
3969 if distinct && arg_length > 1 { "distinct " } else { "" },
3970 pluralize!(arg_length)
3971 ),
3972 }
3973 };
3974
3975 let expected_str = args_str(&expected_args, &found_args);
3976 let found_str = args_str(&found_args, &expected_args);
3977
3978 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!(
3979 self.dcx(),
3980 span,
3981 E0593,
3982 "{} is expected to take {}, but it takes {}",
3983 kind,
3984 expected_str,
3985 found_str,
3986 );
3987
3988 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}"));
3989
3990 if let Some(found_span) = found_span {
3991 err.span_label(found_span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("takes {0}", found_str))
})format!("takes {found_str}"));
3992
3993 if found_args.is_empty() && is_closure {
3997 let underscores = ::alloc::vec::from_elem_global("_", expected_args.len())vec!["_"; expected_args.len()].join(", ");
3998 err.span_suggestion_verbose(
3999 closure_arg_span.unwrap_or(found_span),
4000 ::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!(
4001 "consider changing the closure to take and ignore the expected argument{}",
4002 pluralize!(expected_args.len())
4003 ),
4004 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", underscores))
})format!("|{underscores}|"),
4005 Applicability::MachineApplicable,
4006 );
4007 }
4008
4009 if let &[ArgKind::Tuple(_, ref fields)] = &found_args[..] {
4010 if fields.len() == expected_args.len() {
4011 let sugg = fields
4012 .iter()
4013 .map(|(name, _)| name.to_owned())
4014 .collect::<Vec<String>>()
4015 .join(", ");
4016 err.span_suggestion_verbose(
4017 found_span,
4018 "change the closure to take multiple arguments instead of a single tuple",
4019 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("|{0}|", sugg))
})format!("|{sugg}|"),
4020 Applicability::MachineApplicable,
4021 );
4022 }
4023 }
4024 if let &[ArgKind::Tuple(_, ref fields)] = &expected_args[..]
4025 && fields.len() == found_args.len()
4026 && is_closure
4027 {
4028 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!(
4029 "|({}){}|",
4030 found_args
4031 .iter()
4032 .map(|arg| match arg {
4033 ArgKind::Arg(name, _) => name.to_owned(),
4034 _ => "_".to_owned(),
4035 })
4036 .collect::<Vec<String>>()
4037 .join(", "),
4038 if found_args.iter().any(|arg| match arg {
4040 ArgKind::Arg(_, ty) => ty != "_",
4041 _ => false,
4042 }) {
4043 format!(
4044 ": ({})",
4045 fields
4046 .iter()
4047 .map(|(_, ty)| ty.to_owned())
4048 .collect::<Vec<String>>()
4049 .join(", ")
4050 )
4051 } else {
4052 String::new()
4053 },
4054 );
4055 err.span_suggestion_verbose(
4056 found_span,
4057 "change the closure to accept a tuple instead of individual arguments",
4058 sugg,
4059 Applicability::MachineApplicable,
4060 );
4061 }
4062 }
4063
4064 err
4065 }
4066
4067 pub fn type_implements_fn_trait(
4071 &self,
4072 param_env: ty::ParamEnv<'tcx>,
4073 ty: ty::Binder<'tcx, Ty<'tcx>>,
4074 polarity: ty::ClausePolarity,
4075 ) -> Result<(ty::ClosureKind, ty::Binder<'tcx, Ty<'tcx>>), ()> {
4076 self.commit_if_ok(|_| {
4077 for trait_def_id in [
4078 self.tcx.lang_items().fn_trait(),
4079 self.tcx.lang_items().fn_mut_trait(),
4080 self.tcx.lang_items().fn_once_trait(),
4081 ] {
4082 let Some(trait_def_id) = trait_def_id else { continue };
4083 let var = self.next_ty_var(DUMMY_SP);
4086 let trait_ref = ty::TraitRef::new(self.tcx, trait_def_id, [ty.skip_binder(), var]);
4088 let obligation = Obligation::new(
4089 self.tcx,
4090 ObligationCause::dummy(),
4091 param_env,
4092 ty.rebind(ty::TraitClause { trait_ref, polarity }),
4093 );
4094 let ocx = ObligationCtxt::new(self);
4095 ocx.register_obligation(obligation);
4096 if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
4097 return Ok((
4098 self.tcx
4099 .fn_trait_kind_from_def_id(trait_def_id)
4100 .expect("expected to map DefId to ClosureKind"),
4101 ty.rebind(self.deeply_resolve_ignoring_regions(var)),
4102 ));
4103 }
4104 }
4105
4106 Err(())
4107 })
4108 }
4109
4110 fn report_not_const_evaluatable_error(
4111 &self,
4112 obligation: &PredicateObligation<'tcx>,
4113 span: Span,
4114 ) -> Result<Diag<'a>, ErrorGuaranteed> {
4115 if !self.tcx.features().generic_const_exprs() && !self.tcx.features().gca() {
4116 let guar = self
4117 .dcx()
4118 .struct_span_err(span, "constant expression depends on a generic parameter")
4119 .with_note("this may fail depending on what value the parameter takes")
4126 .emit_err();
4127 return Err(guar);
4128 }
4129
4130 match obligation.predicate.kind().skip_binder() {
4131 ty::PredicateKind::Clause(ty::ClauseKind::ConstEvaluatable(ct)) => match ct.kind() {
4132 ty::ConstKind::Alias(_, alias_const) => {
4133 let mut err =
4134 self.dcx().struct_span_err(span, "unconstrained generic constant");
4135
4136 let const_span = alias_const.kind.def_span(self.tcx);
4137 let const_ty = alias_const.type_of(self.tcx).skip_norm_wip();
4138
4139 let msg = "try adding a `where` bound";
4140 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(const_span) {
4141 let code = if const_ty == self.tcx.types.usize {
4142 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); {0}]:", snippet))
})format!("[(); {snippet}]:")
4143 } else if let ty::AliasConstKind::Anon { def_id } = alias_const.kind
4144 && let Some(local_def_id) = def_id.as_local()
4145 && let Some(local_body) = self.tcx.hir_maybe_body_owned_by(local_def_id)
4146 && expr_needs_parens(local_body.value)
4147 {
4148 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); ({0}) as usize]:", snippet))
})format!("[(); ({snippet}) as usize]:")
4149 } else {
4150 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("[(); {0} as usize]:", snippet))
})format!("[(); {snippet} as usize]:")
4151 };
4152
4153 let suggestion_def_id = if let ObligationCauseCode::CompareImplItem {
4154 trait_item_def_id,
4155 ..
4156 } = obligation.cause.code()
4157 {
4158 trait_item_def_id.as_local()
4159 } else {
4160 Some(obligation.cause.body_def_id)
4161 };
4162
4163 if let Some(suggestion_def_id) = suggestion_def_id
4164 && let Some(generics) = self.tcx.hir_get_generics(suggestion_def_id)
4165 {
4166 err.span_suggestion_verbose(
4167 generics.tail_span_for_predicate_suggestion(),
4168 msg,
4169 ::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()),
4170 Applicability::MaybeIncorrect,
4171 );
4172 } else {
4173 err.help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: where {1}", msg, code))
})format!("{msg}: where {code}"));
4174 };
4175 } else {
4176 err.help(msg);
4177 }
4178 Ok(err)
4179 }
4180 ty::ConstKind::Expr(_) => {
4181 let err = self
4182 .dcx()
4183 .struct_span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("unconstrained generic constant `{0}`",
ct))
})format!("unconstrained generic constant `{ct}`"));
4184 Ok(err)
4185 }
4186 _ => {
4187 ::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:?}`");
4188 }
4189 },
4190 _ => {
4191 ::rustc_span::macros::bug_impl(Some(span),
format_args!("unexpected non-ConstEvaluatable predicate, this should not be reachable"),
Location::caller())span_bug!(
4192 span,
4193 "unexpected non-ConstEvaluatable predicate, this should not be reachable"
4194 )
4195 }
4196 }
4197 }
4198}