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