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