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