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