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