1use std::borrow::Cow;
49use std::ops::ControlFlow;
50use std::path::PathBuf;
51use std::{cmp, fmt, iter};
52
53use rustc_abi::ExternAbi;
54use rustc_attr_ir::diagnostic::{CustomDiagnostic, Directive, FormatArgs};
55use rustc_attr_ir::find_attr;
56use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
57use rustc_errors::{
58 Applicability, Diag, DiagStyledString, IntoDiagArg, MultiSpan, StringPart, pluralize,
59};
60use rustc_hir as hir;
61use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
62use rustc_hir::intravisit::Visitor;
63use rustc_infer::infer::DefineOpaqueTypes;
64use rustc_macros::extension;
65use rustc_middle::traits::PatternOriginExpr;
66use rustc_middle::ty::error::{ExpectedFound, TypeError, TypeErrorToStringExt};
67use rustc_middle::ty::print::{PrintTraitRefExt as _, WrapBinderMode, with_forced_trimmed_paths};
68use rustc_middle::ty::{
69 self, IsRigid, List, Mutability, ParamEnv, Region, Ty, TyCtxt, TypeFoldable,
70 TypeSuperVisitable, TypeVisitable, TypeVisitableExt, Unnormalized,
71};
72use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, Pos, Span, bug, sym};
73use thin_vec::ThinVec;
74use tracing::{debug, instrument};
75
76use crate::diagnostics::{ObligationCauseFailureCode, TypeErrorAdditionalDiags};
77use crate::error_reporting::TypeErrCtxt;
78use crate::error_reporting::traits::ambiguity::{
79 CandidateSource, compute_applicable_impls_for_diagnostics,
80};
81use crate::infer;
82use crate::infer::relate::{self, RelateResult, TypeRelation};
83use crate::infer::{InferCtxt, InferCtxtExt as _, TypeTrace, ValuePairs};
84use crate::traits::{
85 MatchExpressionArmCause, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
86 specialization_graph,
87};
88
89mod note_and_explain;
90mod suggest;
91
92pub mod need_type_info;
93pub mod nice_region_error;
94pub mod region;
95
96fn escape_literal(s: &str) -> String {
99 let mut escaped = String::with_capacity(s.len());
100 let mut chrs = s.chars().peekable();
101 while let Some(first) = chrs.next() {
102 match (first, chrs.peek()) {
103 ('\\', Some(&delim @ '"') | Some(&delim @ '\'')) => {
104 escaped.push('\\');
105 escaped.push(delim);
106 chrs.next();
107 }
108 ('"' | '\'', _) => {
109 escaped.push('\\');
110 escaped.push(first)
111 }
112 (c, _) => escaped.push(c),
113 };
114 }
115 escaped
116}
117
118impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
119 fn normalize_fn_sig(
120 &self,
121 fn_sig: Unnormalized<'tcx, ty::PolyFnSig<'tcx>>,
122 ) -> ty::PolyFnSig<'tcx> {
123 let Some(param_env) = self.param_env else {
124 return fn_sig.skip_normalization();
125 };
126
127 if fn_sig.skip_normalization().has_escaping_bound_vars() {
128 return fn_sig.skip_normalization();
129 }
130
131 self.probe(|_| {
132 let ocx = ObligationCtxt::new(self);
133 let normalized_fn_sig = ocx.normalize(&ObligationCause::dummy(), param_env, fn_sig);
134 if ocx.evaluate_obligations_error_on_ambiguity().no_errors() {
135 let normalized_fn_sig = self.deeply_resolve_ignoring_regions(normalized_fn_sig);
136 if !normalized_fn_sig.has_infer() {
137 return normalized_fn_sig;
138 }
139 }
140 fn_sig.skip_normalization()
141 })
142 }
143
144 pub fn type_error_struct_with_diag<M>(
155 &self,
156 sp: Span,
157 mk_diag: M,
158 actual_ty: Ty<'tcx>,
159 ) -> Diag<'a>
160 where
161 M: FnOnce(String) -> Diag<'a>,
162 {
163 let actual_ty = self.deeply_resolve_ignoring_regions(actual_ty);
164 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:164",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(164u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("type_error_struct_with_diag({0:?}, {1:?})",
sp, actual_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
165
166 let mut err = mk_diag(self.ty_to_string(actual_ty));
167
168 if actual_ty.references_error() {
170 err.downgrade_to_delayed_bug();
171 }
172
173 err
174 }
175
176 pub fn report_mismatched_types(
177 &self,
178 cause: &ObligationCause<'tcx>,
179 param_env: ty::ParamEnv<'tcx>,
180 expected: Ty<'tcx>,
181 actual: Ty<'tcx>,
182 err: TypeError<'tcx>,
183 ) -> Diag<'a> {
184 let mut diag = self.report_and_explain_type_error(
185 TypeTrace::types(cause, expected, actual),
186 param_env,
187 err,
188 );
189
190 self.suggest_param_env_shadowing(&mut diag, expected, actual, param_env);
191
192 diag
193 }
194
195 pub fn report_mismatched_consts(
196 &self,
197 cause: &ObligationCause<'tcx>,
198 param_env: ty::ParamEnv<'tcx>,
199 expected: ty::Const<'tcx>,
200 actual: ty::Const<'tcx>,
201 err: TypeError<'tcx>,
202 ) -> Diag<'a> {
203 self.report_and_explain_type_error(
204 TypeTrace::consts(cause, expected, actual),
205 param_env,
206 err,
207 )
208 }
209
210 fn check_and_note_conflicting_crates(&self, err: &mut Diag<'_>, terr: TypeError<'tcx>) -> bool {
212 match terr {
213 TypeError::Sorts(ref exp_found) => {
214 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
217 (exp_found.expected.kind(), exp_found.found.kind())
218 {
219 return self.check_same_definition_different_crate(
220 err,
221 exp_adt.did(),
222 [found_adt.did()].into_iter(),
223 |did| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self.tcx.def_span(did)]))vec![self.tcx.def_span(did)],
224 "type",
225 );
226 }
227 }
228 TypeError::Traits(ref exp_found) => {
229 return self.check_same_definition_different_crate(
230 err,
231 exp_found.expected,
232 [exp_found.found].into_iter(),
233 |did| ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[self.tcx.def_span(did)]))vec![self.tcx.def_span(did)],
234 "trait",
235 );
236 }
237 _ => (), }
239 false
240 }
241
242 fn suggest_param_env_shadowing(
243 &self,
244 diag: &mut Diag<'_>,
245 expected: Ty<'tcx>,
246 found: Ty<'tcx>,
247 param_env: ty::ParamEnv<'tcx>,
248 ) {
249 let (alias, &def_id, concrete) = match (expected.kind(), found.kind()) {
250 (ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { def_id }, .. }), _) => {
251 (proj, def_id, found)
252 }
253 (_, ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { def_id }, .. })) => {
254 (proj, def_id, expected)
255 }
256 _ => return,
257 };
258
259 let tcx = self.tcx;
260
261 let trait_ref = alias.trait_ref(tcx);
262 let obligation =
263 Obligation::new(tcx, ObligationCause::dummy(), param_env, ty::Binder::dummy(trait_ref));
264
265 let applicable_impls =
266 compute_applicable_impls_for_diagnostics(self.infcx, &obligation, false);
267
268 for candidate in applicable_impls {
269 let impl_def_id = match candidate {
270 CandidateSource::DefId(did) => did,
271 CandidateSource::ParamEnv(_) => continue,
272 };
273
274 let is_shadowed = self.infcx.probe(|_| {
275 let impl_substs = self.infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
276 let impl_trait_ref =
277 tcx.impl_trait_ref(impl_def_id).instantiate(tcx, impl_substs).skip_norm_wip();
278
279 let expected_trait_ref = alias.trait_ref(tcx);
280
281 if let Err(_) = self.infcx.eq_raw(
282 &ObligationCause::dummy(),
283 param_env,
284 DefineOpaqueTypes::No,
285 expected_trait_ref,
286 impl_trait_ref,
287 ) {
288 return false;
289 }
290
291 let leaf_def = match specialization_graph::assoc_def(tcx, impl_def_id, def_id) {
292 Ok(leaf) => leaf,
293 Err(_) => return false,
294 };
295
296 let trait_def_id = alias.trait_def_id(tcx);
297 let rebased_args = alias.args.rebase_onto(tcx, trait_def_id, impl_substs);
298
299 if !leaf_def.item.defaultness(tcx).has_value() {
302 return false;
303 }
304
305 let impl_item_def_id = leaf_def.item.def_id;
306 if !tcx.check_args_compatible(impl_item_def_id, rebased_args) {
307 return false;
308 }
309 let impl_assoc_ty =
310 tcx.type_of(impl_item_def_id).instantiate(tcx, rebased_args).skip_norm_wip();
311
312 self.infcx.can_eq(param_env, impl_assoc_ty, concrete)
313 });
314
315 if is_shadowed {
316 diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the associated type `{0}` is defined as `{1}` in the implementation, but the where-bound `{2}` shadows this definition\nsee issue #152409 <https://github.com/rust-lang/rust/issues/152409> for more information",
self.ty_to_string(alias.to_ty(tcx, ty::IsRigid::No)),
self.ty_to_string(concrete),
self.ty_to_string(alias.self_ty())))
})format!(
317 "the associated type `{}` is defined as `{}` in the implementation, \
318 but the where-bound `{}` shadows this definition\n\
319 see issue #152409 <https://github.com/rust-lang/rust/issues/152409> for more information",
320 self.ty_to_string(alias.to_ty(tcx, ty::IsRigid::No)),
321 self.ty_to_string(concrete),
322 self.ty_to_string(alias.self_ty())
323 ));
324 return;
325 }
326 }
327 }
328
329 fn note_error_origin(
330 &self,
331 err: &mut Diag<'_>,
332 cause: &ObligationCause<'tcx>,
333 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
334 terr: TypeError<'tcx>,
335 param_env: Option<ParamEnv<'tcx>>,
336 ) {
337 match *cause.code() {
338 ObligationCauseCode::Pattern {
339 origin_expr: Some(origin_expr),
340 span: Some(span),
341 root_ty,
342 } => {
343 let expected_ty = self.deeply_resolve_ignoring_regions(root_ty);
344 if !#[allow(non_exhaustive_omitted_patterns)] match expected_ty.kind() {
ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)) => true,
_ => false,
}matches!(
345 expected_ty.kind(),
346 ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_))
347 ) {
348 if span.desugaring_kind() == Some(DesugaringKind::ForLoop)
350 && let ty::Adt(def, args) = expected_ty.kind()
351 && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option)
352 {
353 err.span_label(
354 span,
355 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this is an iterator with items of type `{0}`",
args.type_at(0)))
})format!("this is an iterator with items of type `{}`", args.type_at(0)),
356 );
357 } else if !span.overlaps(cause.span) {
358 let expected_ty = self.tcx.short_string(expected_ty, err.long_ty_path());
359 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this expression has type `{0}`",
expected_ty))
})format!("this expression has type `{expected_ty}`"));
360 }
361 }
362 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
363 && let Ok(mut peeled_snippet) =
364 self.tcx.sess.source_map().span_to_snippet(origin_expr.peeled_span)
365 {
366 if origin_expr.peeled_prefix_suggestion_parentheses {
371 peeled_snippet = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", peeled_snippet))
})format!("({peeled_snippet})");
372 }
373
374 if expected_ty.boxed_ty() == Some(found) {
377 err.span_suggestion_verbose(
378 span,
379 "consider dereferencing the boxed value",
380 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("*{0}", peeled_snippet))
})format!("*{peeled_snippet}"),
381 Applicability::MachineApplicable,
382 );
383 } else if let Some(param_env) = param_env
384 && let Some(prefix) = self.should_deref_suggestion_on_mismatch(
385 param_env,
386 found,
387 expected_ty,
388 origin_expr,
389 )
390 {
391 err.span_suggestion_verbose(
392 span,
393 "consider dereferencing to access the inner value using the `Deref` trait",
394 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", prefix, peeled_snippet))
})format!("{prefix}{peeled_snippet}"),
395 Applicability::MaybeIncorrect,
396 );
397 }
398 }
399 }
400 ObligationCauseCode::Pattern { origin_expr: None, span: Some(span), .. } => {
401 err.span_label(span, "expected due to this");
402 }
403 ObligationCauseCode::BlockTailExpression(
404 _,
405 hir::MatchSource::TryDesugar(scrut_hir_id),
406 ) => {
407 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
408 let scrut_expr = self.tcx.hir_expect_expr(scrut_hir_id);
409 let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
410 let arg_expr = args.first().expect("try desugaring call w/out arg");
411 self.typeck_results
412 .as_ref()
413 .and_then(|typeck_results| typeck_results.expr_ty_opt(arg_expr))
414 } else {
415 ::rustc_span::macros::bug_impl(None,
format_args!("try desugaring w/out call expr as scrutinee"),
Location::caller());bug!("try desugaring w/out call expr as scrutinee");
416 };
417
418 match scrut_ty {
419 Some(ty) if expected == ty => {
420 let source_map = self.tcx.sess.source_map();
421 err.span_suggestion_short(
422 source_map.end_point(cause.span),
423 "try removing this `?`",
424 "",
425 Applicability::MachineApplicable,
426 );
427 }
428 _ => {}
429 }
430 }
431 }
432 ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
433 arm_block_id,
434 arm_span,
435 arm_ty,
436 prior_arm_block_id,
437 prior_arm_span,
438 prior_arm_ty,
439 source,
440 ref prior_non_diverging_arms,
441 scrut_span,
442 expr_span,
443 ..
444 }) => match source {
445 hir::MatchSource::TryDesugar(scrut_hir_id) => {
446 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
447 let scrut_expr = self.tcx.hir_expect_expr(scrut_hir_id);
448 let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
449 let arg_expr = args.first().expect("try desugaring call w/out arg");
450 self.typeck_results
451 .as_ref()
452 .and_then(|typeck_results| typeck_results.expr_ty_opt(arg_expr))
453 } else {
454 ::rustc_span::macros::bug_impl(None,
format_args!("try desugaring w/out call expr as scrutinee"),
Location::caller());bug!("try desugaring w/out call expr as scrutinee");
455 };
456
457 match scrut_ty {
458 Some(ty) if expected == ty => {
459 let source_map = self.tcx.sess.source_map();
460 err.span_suggestion_short(
461 source_map.end_point(cause.span),
462 "try removing this `?`",
463 "",
464 Applicability::MachineApplicable,
465 );
466 }
467 _ => {}
468 }
469 }
470 }
471 _ => {
472 let t = self.deeply_resolve_ignoring_regions(match exp_found {
474 Some(ty::error::ExpectedFound { expected, .. }) => expected,
475 _ => prior_arm_ty,
476 });
477 let source_map = self.tcx.sess.source_map();
478 let mut any_multiline_arm = source_map.is_multiline(arm_span);
479 if prior_non_diverging_arms.len() <= 4 {
480 for sp in prior_non_diverging_arms {
481 any_multiline_arm |= source_map.is_multiline(*sp);
482 err.span_label(*sp, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this is found to be of type `{0}`",
t))
})format!("this is found to be of type `{t}`"));
483 }
484 } else if let Some(sp) = prior_non_diverging_arms.last() {
485 any_multiline_arm |= source_map.is_multiline(*sp);
486 err.span_label(
487 *sp,
488 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("this and all prior arms are found to be of type `{0}`",
t))
})format!("this and all prior arms are found to be of type `{t}`"),
489 );
490 }
491 let outer = if any_multiline_arm || !source_map.is_multiline(expr_span) {
492 expr_span.shrink_to_lo().to(scrut_span)
495 } else {
496 expr_span
497 };
498 let msg = "`match` arms have incompatible types";
499 err.span_label(outer, msg);
500 if let Some(subdiag) = self.suggest_remove_semi_or_return_binding(
501 prior_arm_block_id,
502 prior_arm_ty,
503 prior_arm_span,
504 arm_block_id,
505 arm_ty,
506 arm_span,
507 ) {
508 err.subdiagnostic(subdiag);
509 }
510 }
511 },
512 ObligationCauseCode::IfExpression { expr_id, .. } => {
513 let hir::Node::Expr(&hir::Expr {
514 kind: hir::ExprKind::If(cond_expr, then_expr, Some(else_expr)),
515 span: expr_span,
516 ..
517 }) = self.tcx.hir_node(expr_id)
518 else {
519 return;
520 };
521 let then_span = self.find_block_span_from_hir_id(then_expr.hir_id);
522 let then_ty = self
523 .typeck_results
524 .as_ref()
525 .expect("if expression only expected inside FnCtxt")
526 .expr_ty(then_expr);
527 let else_span = self.find_block_span_from_hir_id(else_expr.hir_id);
528 let else_ty = self
529 .typeck_results
530 .as_ref()
531 .expect("if expression only expected inside FnCtxt")
532 .expr_ty(else_expr);
533 if let hir::ExprKind::If(_cond, _then, None) = else_expr.kind
534 && else_ty.is_unit()
535 {
536 err.note("`if` expressions without `else` evaluate to `()`");
538 err.note("consider adding an `else` block that evaluates to the expected type");
539 }
540 err.span_label(then_span, "expected because of this");
541
542 let outer_span = if self.tcx.sess.source_map().is_multiline(expr_span) {
543 if then_span.hi() == expr_span.hi() || else_span.hi() == expr_span.hi() {
544 Some(expr_span.shrink_to_lo().to(cond_expr.peel_drop_temps().span))
547 } else {
548 Some(expr_span)
549 }
550 } else {
551 None
552 };
553 if let Some(sp) = outer_span {
554 err.span_label(sp, "`if` and `else` have incompatible types");
555 }
556
557 let then_id = if let hir::ExprKind::Block(then_blk, _) = then_expr.kind {
558 then_blk.hir_id
559 } else {
560 then_expr.hir_id
561 };
562 let else_id = if let hir::ExprKind::Block(else_blk, _) = else_expr.kind {
563 else_blk.hir_id
564 } else {
565 else_expr.hir_id
566 };
567 if let Some(subdiag) = self.suggest_remove_semi_or_return_binding(
568 Some(then_id),
569 then_ty,
570 then_span,
571 Some(else_id),
572 else_ty,
573 else_span,
574 ) {
575 err.subdiagnostic(subdiag);
576 }
577 }
578 ObligationCauseCode::LetElse => {
579 err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
580 err.help("...or use `match` instead of `let...else`");
581 }
582 _ => {
583 if let ObligationCauseCode::WhereClause(_, span)
584 | ObligationCauseCode::WhereClauseInExpr(_, span, ..) =
585 cause.code().peel_derives()
586 && !span.is_dummy()
587 && let TypeError::RegionsPlaceholderMismatch = terr
588 {
589 err.span_note(*span, "the lifetime requirement is introduced here");
590 }
591 }
592 }
593 }
594
595 fn should_deref_suggestion_on_mismatch(
598 &self,
599 param_env: ParamEnv<'tcx>,
600 deref_to: Ty<'tcx>,
601 deref_from: Ty<'tcx>,
602 origin_expr: PatternOriginExpr,
603 ) -> Option<String> {
604 let Some((num_derefs, (after_deref_ty, _))) = (self.autoderef_steps)(deref_from)
612 .into_iter()
613 .enumerate()
614 .find(|(_, (ty, _))| self.infcx.can_eq(param_env, *ty, deref_to))
615 else {
616 return None;
617 };
618
619 if num_derefs <= origin_expr.peeled_count {
620 return None;
621 }
622
623 let deref_part = "*".repeat(num_derefs - origin_expr.peeled_count);
624
625 if deref_from.is_ref() && !after_deref_ty.is_ref() {
628 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", deref_part))
})format!("&{deref_part}"))
629 } else {
630 Some(deref_part)
631 }
632 }
633
634 fn highlight_outer(
648 &self,
649 value: &mut DiagStyledString,
650 other_value: &mut DiagStyledString,
651 name: String,
652 args: &[ty::GenericArg<'tcx>],
653 pos: usize,
654 other_ty: Ty<'tcx>,
655 ) {
656 value.push_highlighted(name);
659
660 if args.is_empty() {
661 return;
662 }
663 value.push_highlighted("<");
664
665 for (i, arg) in args.iter().enumerate() {
666 if i > 0 {
667 value.push_normal(", ");
668 }
669
670 match arg.kind() {
671 ty::GenericArgKind::Lifetime(lt) => {
672 let s = lt.to_string();
673 value.push_normal(if s.is_empty() { "'_" } else { &s });
674 }
675 ty::GenericArgKind::Const(ct) => {
676 value.push_normal(ct.to_string());
677 }
678 ty::GenericArgKind::Type(type_arg) => {
681 if i == pos {
682 let values = self.cmp(type_arg, other_ty);
683 value.0.extend((values.0).0);
684 other_value.0.extend((values.1).0);
685 } else {
686 value.push_highlighted(type_arg.to_string());
687 }
688 }
689 }
690 }
691
692 value.push_highlighted(">");
693 }
694
695 fn cmp_type_arg(
716 &self,
717 t1_out: &mut DiagStyledString,
718 t2_out: &mut DiagStyledString,
719 path: String,
720 args: &[ty::GenericArg<'tcx>],
721 other_path: String,
722 other_ty: Ty<'tcx>,
723 ) -> bool {
724 for (i, arg) in args.iter().enumerate() {
725 if let Some(ta) = arg.as_type() {
726 if ta == other_ty {
727 self.highlight_outer(t1_out, t2_out, path, args, i, other_ty);
728 return true;
729 }
730 if let ty::Adt(def, _) = ta.kind() {
731 let path_ = self.tcx.def_path_str(def.did());
732 if path_ == other_path {
733 self.highlight_outer(t1_out, t2_out, path, args, i, other_ty);
734 return true;
735 }
736 }
737 }
738 }
739 false
740 }
741
742 fn push_comma(
744 &self,
745 value: &mut DiagStyledString,
746 other_value: &mut DiagStyledString,
747 pos: usize,
748 ) {
749 if pos > 0 {
750 value.push_normal(", ");
751 other_value.push_normal(", ");
752 }
753 }
754
755 fn cmp_fn_sig(
757 &self,
758 sig1: ty::PolyFnSig<'tcx>,
759 fn_def1: Option<(DefId, Option<ty::GenericArgs<'tcx>>)>,
760 sig2: ty::PolyFnSig<'tcx>,
761 fn_def2: Option<(DefId, Option<ty::GenericArgs<'tcx>>)>,
762 ) -> (DiagStyledString, DiagStyledString) {
763 let sig1 = self.normalize_fn_sig(Unnormalized::new_wip(sig1));
764 let sig2 = self.normalize_fn_sig(Unnormalized::new_wip(sig2));
765
766 let get_lifetimes = |sig| {
767 use rustc_hir::def::Namespace;
768 let (sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
769 .name_all_regions(&sig, WrapBinderMode::ForAll)
770 .unwrap();
771 let lts: Vec<String> =
772 reg.into_items().map(|(_, kind)| kind.to_string()).into_sorted_stable_ord();
773 (if lts.is_empty() { String::new() } else { ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("for<{0}> ", lts.join(", ")))
})format!("for<{}> ", lts.join(", ")) }, sig)
774 };
775
776 let (lt1, sig1) = get_lifetimes(sig1);
777 let (lt2, sig2) = get_lifetimes(sig2);
778
779 let mut values =
781 (DiagStyledString::normal("".to_string()), DiagStyledString::normal("".to_string()));
782
783 let fn_item_prefix_and_safety = |fn_def, sig: ty::FnSig<'_>| match fn_def {
786 None => ("", sig.safety().prefix_str()),
787 Some((did, _)) => {
788 if self.tcx.codegen_fn_attrs(did).safe_target_features {
789 ("#[target_feature(..)] ", "")
790 } else {
791 ("", sig.safety().prefix_str())
792 }
793 }
794 };
795 let (prefix1, safety1) = fn_item_prefix_and_safety(fn_def1, sig1);
796 let (prefix2, safety2) = fn_item_prefix_and_safety(fn_def2, sig2);
797 values.0.push(prefix1, prefix1 != prefix2);
798 values.1.push(prefix2, prefix1 != prefix2);
799
800 let lifetime_diff = lt1 != lt2;
803 values.0.push(lt1, lifetime_diff);
804 values.1.push(lt2, lifetime_diff);
805
806 values.0.push(safety1, safety1 != safety2);
809 values.1.push(safety2, safety1 != safety2);
810
811 if sig1.abi() != ExternAbi::Rust {
814 values.0.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("extern {0} ", sig1.abi()))
})format!("extern {} ", sig1.abi()), sig1.abi() != sig2.abi());
815 }
816 if sig2.abi() != ExternAbi::Rust {
817 values.1.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("extern {0} ", sig2.abi()))
})format!("extern {} ", sig2.abi()), sig1.abi() != sig2.abi());
818 }
819
820 values.0.push_normal("fn(");
823 values.1.push_normal("fn(");
824
825 let len1 = sig1.inputs().len();
828 let len2 = sig2.inputs().len();
829 let splatted_arg_index1 = sig1.splatted().map(usize::from);
830 let splatted_arg_index2 = sig2.splatted().map(usize::from);
831 if len1 == len2 {
832 for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
833 self.push_comma(&mut values.0, &mut values.1, i);
834 if Some(i) == splatted_arg_index1 {
835 values.0.push("#[rustc_splat]", splatted_arg_index1 != splatted_arg_index2);
836 values.0.push_normal(" ");
837 }
838 if Some(i) == splatted_arg_index2 {
839 values.1.push("#[rustc_splat]", splatted_arg_index1 != splatted_arg_index2);
840 values.1.push_normal(" ");
841 }
842 let (x1, x2) = self.cmp(*l, *r);
843 (values.0).0.extend(x1.0);
844 (values.1).0.extend(x2.0);
845 }
846 } else {
847 for (i, l) in sig1.inputs().iter().enumerate() {
848 values.0.push_highlighted(l.to_string());
849 if i != len1 - 1 {
850 values.0.push_highlighted(", ");
851 }
852 }
853 for (i, r) in sig2.inputs().iter().enumerate() {
854 values.1.push_highlighted(r.to_string());
855 if i != len2 - 1 {
856 values.1.push_highlighted(", ");
857 }
858 }
859 }
860
861 if sig1.c_variadic() {
862 if len1 > 0 {
863 values.0.push_normal(", ");
864 }
865 values.0.push("...", !sig2.c_variadic());
866 }
867 if sig2.c_variadic() {
868 if len2 > 0 {
869 values.1.push_normal(", ");
870 }
871 values.1.push("...", !sig1.c_variadic());
872 }
873
874 values.0.push_normal(")");
877 values.1.push_normal(")");
878
879 let output1 = sig1.output();
882 let output2 = sig2.output();
883 let (x1, x2) = self.cmp(output1, output2);
884 let output_diff = x1 != x2;
885 if !output1.is_unit() || output_diff {
886 values.0.push_normal(" -> ");
887 (values.0).0.extend(x1.0);
888 }
889 if !output2.is_unit() || output_diff {
890 values.1.push_normal(" -> ");
891 (values.1).0.extend(x2.0);
892 }
893
894 let fmt = |did, args| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{{0}}}",
self.tcx.def_path_str_with_args(did, args)))
})format!(" {{{}}}", self.tcx.def_path_str_with_args(did, args));
895
896 match (fn_def1, fn_def2) {
897 (Some((fn_def1, Some(fn_args1))), Some((fn_def2, Some(fn_args2)))) => {
898 let path1 = fmt(fn_def1, fn_args1);
899 let path2 = fmt(fn_def2, fn_args2);
900 let same_path = path1 == path2;
901 values.0.push(path1, !same_path);
902 values.1.push(path2, !same_path);
903 }
904 (Some((fn_def1, Some(fn_args1))), None) => {
905 values.0.push_highlighted(fmt(fn_def1, fn_args1));
906 }
907 (None, Some((fn_def2, Some(fn_args2)))) => {
908 values.1.push_highlighted(fmt(fn_def2, fn_args2));
909 }
910 _ => {}
911 }
912
913 values
914 }
915
916 pub fn cmp_traits(
917 &self,
918 def_id1: DefId,
919 args1: &[ty::GenericArg<'tcx>],
920 def_id2: DefId,
921 args2: &[ty::GenericArg<'tcx>],
922 ) -> (DiagStyledString, DiagStyledString) {
923 let mut values = (DiagStyledString::new(), DiagStyledString::new());
924
925 if def_id1 != def_id2 {
926 values.0.push_highlighted(self.tcx.def_path_str(def_id1).as_str());
927 values.1.push_highlighted(self.tcx.def_path_str(def_id2).as_str());
928 } else {
929 values.0.push_normal(self.tcx.item_name(def_id1).as_str());
930 values.1.push_normal(self.tcx.item_name(def_id2).as_str());
931 }
932
933 if args1.len() != args2.len() {
934 let (pre, post) = if args1.len() > 0 { ("<", ">") } else { ("", "") };
935 values.0.push_normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}{2}",
args1.iter().map(|a|
a.to_string()).collect::<Vec<_>>().join(", "), pre, post))
})format!(
936 "{pre}{}{post}",
937 args1.iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ")
938 ));
939 let (pre, post) = if args2.len() > 0 { ("<", ">") } else { ("", "") };
940 values.1.push_normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{1}{0}{2}",
args2.iter().map(|a|
a.to_string()).collect::<Vec<_>>().join(", "), pre, post))
})format!(
941 "{pre}{}{post}",
942 args2.iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ")
943 ));
944 return values;
945 }
946
947 if args1.len() > 0 {
948 values.0.push_normal("<");
949 values.1.push_normal("<");
950 }
951 for (i, (a, b)) in std::iter::zip(args1, args2).enumerate() {
952 let a_str = a.to_string();
953 let b_str = b.to_string();
954 if let (Some(a), Some(b)) = (a.as_type(), b.as_type()) {
955 let (a, b) = self.cmp(a, b);
956 values.0.0.extend(a.0);
957 values.1.0.extend(b.0);
958 } else if a_str != b_str {
959 values.0.push_highlighted(a_str);
960 values.1.push_highlighted(b_str);
961 } else {
962 values.0.push_normal(a_str);
963 values.1.push_normal(b_str);
964 }
965 if i + 1 < args1.len() {
966 values.0.push_normal(", ");
967 values.1.push_normal(", ");
968 }
969 }
970 if args1.len() > 0 {
971 values.0.push_normal(">");
972 values.1.push_normal(">");
973 }
974 values
975 }
976
977 fn lifetime_display(&self, lifetime: Region<'_>) -> String {
978 let s = lifetime.to_string();
979 if s.is_empty() { "'_".to_string() } else { s }
980 }
981
982 fn compare_generics(
983 &self,
984 mut values: &mut (DiagStyledString, DiagStyledString),
985 sub1: &[ty::GenericArg<'tcx>],
986 sub2: &[ty::GenericArg<'tcx>],
987 ) {
988 let len = sub1.len();
989 if sub1.len() > 0 {
991 values.0.push_normal("<");
992 }
993 if sub2.len() > 0 {
994 values.1.push_normal("<");
995 }
996
997 if sub1.len() == sub2.len() {
998 for (i, (arg1, arg2)) in sub1.iter().zip(sub2).enumerate().take(len) {
999 self.push_comma(&mut values.0, &mut values.1, i);
1000 match (arg1.kind(), arg2.kind()) {
1001 (ty::GenericArgKind::Lifetime(l1), ty::GenericArgKind::Lifetime(l2)) => {
1018 let l1_str = self.lifetime_display(l1);
1019 let l2_str = self.lifetime_display(l2);
1020 if l1 != l2 {
1021 values.0.push_highlighted(l1_str);
1022 values.1.push_highlighted(l2_str);
1023 } else if l1.is_bound() || self.tcx.sess.opts.verbose {
1024 values.0.push_normal(l1_str);
1025 values.1.push_normal(l2_str);
1026 } else {
1027 values.0.push_normal("'_");
1028 values.1.push_normal("'_");
1029 }
1030 }
1031 (ty::GenericArgKind::Type(ta1), ty::GenericArgKind::Type(ta2)) => {
1032 if ta1 == ta2 && !self.tcx.sess.opts.verbose {
1033 values.0.push_normal("_");
1034 values.1.push_normal("_");
1035 } else {
1036 self.recurse(ta1, ta2, &mut values);
1037 }
1038 }
1039 (ty::GenericArgKind::Const(ca1), ty::GenericArgKind::Const(ca2)) => {
1049 self.maybe_highlight(ca1, ca2, &mut values, self.tcx);
1050 }
1051 _ => {
1054 values.0.push_normal(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", arg1))
})format!("{arg1}"));
1055 values.1.push_normal(&::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", arg2))
})format!("{arg2}"));
1056 }
1057 }
1058 }
1059 } else {
1060 for (value, args) in [(&mut values.0, sub1), (&mut values.1, sub2)] {
1062 for (i, arg) in args.iter().enumerate() {
1063 if i > 0 {
1064 value.push_normal(", ");
1065 }
1066 match arg.kind() {
1067 ty::GenericArgKind::Lifetime(l) => {
1068 let l_str = self.lifetime_display(l);
1069 if l.is_bound() || self.tcx.sess.opts.verbose {
1070 value.push_normal(l_str);
1071 } else {
1072 value.push_normal("'_");
1073 }
1074 }
1075 ty::GenericArgKind::Type(ty) => {
1076 if !self.tcx.sess.opts.verbose {
1077 value.push_normal("_");
1078 } else {
1079 value.push_normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", ty)) })format!("{ty}"));
1080 }
1081 }
1082 ty::GenericArgKind::Const(ca) => {
1083 value.push_normal(::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("{0}", ca)) })format!("{ca}"));
1084 }
1085 }
1086 }
1087 }
1088 }
1089
1090 if sub1.len() > 0 {
1093 values.0.push_normal(">");
1094 }
1095 if sub2.len() > 0 {
1096 values.1.push_normal(">");
1097 }
1098 }
1099
1100 fn recurse(
1101 &self,
1102 t1: Ty<'tcx>,
1103 t2: Ty<'tcx>,
1104 values: &mut (DiagStyledString, DiagStyledString),
1105 ) {
1106 let (x1, x2) = self.cmp(t1, t2);
1107 (values.0).0.extend(x1.0);
1108 (values.1).0.extend(x2.0);
1109 }
1110
1111 fn maybe_highlight<T: Eq + ToString>(
1112 &self,
1113 t1: T,
1114 t2: T,
1115 (buf1, buf2): &mut (DiagStyledString, DiagStyledString),
1116 tcx: TyCtxt<'_>,
1117 ) {
1118 let highlight = t1 != t2;
1119 let (t1, t2) = if highlight || tcx.sess.opts.verbose {
1120 (t1.to_string(), t2.to_string())
1121 } else {
1122 ("_".into(), "_".into())
1124 };
1125 buf1.push(t1, highlight);
1126 buf2.push(t2, highlight);
1127 }
1128
1129 pub fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagStyledString, DiagStyledString) {
1132 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1132",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1132u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("cmp(t1={0}, t1.kind={1:?}, t2={2}, t2.kind={3:?})",
t1, t1.kind(), t2, t2.kind()) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1133
1134 fn fmt_region<'tcx>(region: ty::Region<'tcx>) -> String {
1136 let mut r = region.to_string();
1137 if r == "'_" {
1138 r.clear();
1139 } else {
1140 r.push(' ');
1141 }
1142 ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", r)) })format!("&{r}")
1143 }
1144
1145 fn push_ref<'tcx>(
1146 region: ty::Region<'tcx>,
1147 mutbl: hir::Mutability,
1148 s: &mut DiagStyledString,
1149 ) {
1150 s.push_highlighted(fmt_region(region));
1151 s.push_highlighted(mutbl.prefix_str());
1152 }
1153
1154 fn cmp_ty_refs<'tcx>(
1155 r1: ty::Region<'tcx>,
1156 mut1: hir::Mutability,
1157 r2: ty::Region<'tcx>,
1158 mut2: hir::Mutability,
1159 ss: &mut (DiagStyledString, DiagStyledString),
1160 ) {
1161 let (r1, r2) = (fmt_region(r1), fmt_region(r2));
1162 if r1 != r2 {
1163 ss.0.push_highlighted(r1);
1164 ss.1.push_highlighted(r2);
1165 } else {
1166 ss.0.push_normal(r1);
1167 ss.1.push_normal(r2);
1168 }
1169
1170 if mut1 != mut2 {
1171 ss.0.push_highlighted(mut1.prefix_str());
1172 ss.1.push_highlighted(mut2.prefix_str());
1173 } else {
1174 ss.0.push_normal(mut1.prefix_str());
1175 ss.1.push_normal(mut2.prefix_str());
1176 }
1177 }
1178
1179 match (t1.kind(), t2.kind()) {
1181 (&ty::Adt(def1, sub1_args), &ty::Adt(def2, sub2_args)) => {
1182 let sub1 = sub1_args.as_slice();
1183 let sub2 = sub2_args.as_slice();
1184 let did1 = def1.did();
1185 let did2 = def2.did();
1186
1187 let generics1 = self.tcx.generics_of(did1);
1188 let generics2 = self.tcx.generics_of(did2);
1189
1190 let non_default_after_default = generics1
1191 .check_concrete_type_after_default(self.tcx, sub1_args)
1192 || generics2.check_concrete_type_after_default(self.tcx, sub2_args);
1193 let sub_no_defaults_1 = if non_default_after_default {
1194 generics1.own_args(sub1)
1195 } else {
1196 generics1.own_args_no_defaults(self.tcx, sub1)
1197 };
1198 let sub_no_defaults_2 = if non_default_after_default {
1199 generics2.own_args(sub2)
1200 } else {
1201 generics2.own_args_no_defaults(self.tcx, sub2)
1202 };
1203 let mut values = (DiagStyledString::new(), DiagStyledString::new());
1204 let path1 = self.tcx.def_path_str(did1);
1205 let path2 = self.tcx.def_path_str(did2);
1206 if did1 == did2 {
1207 values.0.push_normal(self.tcx.item_name(did1).to_string());
1216 values.1.push_normal(self.tcx.item_name(did2).to_string());
1217
1218 let len1 = sub_no_defaults_1.len();
1221 let len2 = sub_no_defaults_2.len();
1222 let common_len = cmp::min(len1, len2);
1223 let remainder1 = &sub1[common_len..];
1224 let remainder2 = &sub2[common_len..];
1225 let common_default_params =
1226 iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1227 .filter(|(a, b)| a == b)
1228 .count();
1229 let len = sub1.len() - common_default_params;
1230 self.compare_generics(&mut values, &sub1[..len], &sub2[..len]);
1231 values
1232 } else {
1233 if self.cmp_type_arg(
1239 &mut values.0,
1240 &mut values.1,
1241 path1.clone(),
1242 sub_no_defaults_1,
1243 path2.clone(),
1244 t2,
1245 ) {
1246 return values;
1247 }
1248 if self.cmp_type_arg(
1254 &mut values.1,
1255 &mut values.0,
1256 path2,
1257 sub_no_defaults_2,
1258 path1,
1259 t1,
1260 ) {
1261 return values;
1262 }
1263
1264 let t1_str = t1.to_string();
1271 let t2_str = t2.to_string();
1272 let min_len = t1_str.len().min(t2_str.len());
1273
1274 const SEPARATOR: &str = "::";
1275 let separator_len = SEPARATOR.len();
1276 let split_idx: usize =
1277 iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1278 .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1279 .map(|(mod_str, _)| mod_str.len() + separator_len)
1280 .sum();
1281
1282 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1282",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1282u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("separator_len")
}> =
::tracing::__macro_support::FieldName::new("separator_len");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("split_idx")
}> =
::tracing::__macro_support::FieldName::new("split_idx");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("min_len")
}> =
::tracing::__macro_support::FieldName::new("min_len");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("cmp")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&separator_len)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&split_idx)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&min_len)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?separator_len, ?split_idx, ?min_len, "cmp");
1283
1284 if split_idx >= min_len {
1285 (
1287 DiagStyledString::highlighted(t1_str),
1288 DiagStyledString::highlighted(t2_str),
1289 )
1290 } else {
1291 let (common, uniq1) = t1_str.split_at(split_idx);
1292 let (_, uniq2) = t2_str.split_at(split_idx);
1293 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1293",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1293u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["message",
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("common")
}> =
::tracing::__macro_support::FieldName::new("common");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("uniq1")
}> =
::tracing::__macro_support::FieldName::new("uniq1");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("uniq2")
}> =
::tracing::__macro_support::FieldName::new("uniq2");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("cmp")
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&common)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&uniq1)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&uniq2)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(?common, ?uniq1, ?uniq2, "cmp");
1294
1295 values.0.push_normal(common);
1296 values.0.push_highlighted(uniq1);
1297 values.1.push_normal(common);
1298 values.1.push_highlighted(uniq2);
1299
1300 values
1301 }
1302 }
1303 }
1304
1305 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2)) => {
1307 let mut values = (DiagStyledString::new(), DiagStyledString::new());
1308 cmp_ty_refs(r1, mutbl1, r2, mutbl2, &mut values);
1309 self.recurse(ref_ty1, ref_ty2, &mut values);
1310 values
1311 }
1312 (&ty::Ref(r1, ref_ty1, mutbl1), _) => {
1314 let mut values = (DiagStyledString::new(), DiagStyledString::new());
1315 push_ref(r1, mutbl1, &mut values.0);
1316 self.recurse(ref_ty1, t2, &mut values);
1317 values
1318 }
1319 (_, &ty::Ref(r2, ref_ty2, mutbl2)) => {
1320 let mut values = (DiagStyledString::new(), DiagStyledString::new());
1321 push_ref(r2, mutbl2, &mut values.1);
1322 self.recurse(t1, ref_ty2, &mut values);
1323 values
1324 }
1325
1326 (&ty::Tuple(args1), &ty::Tuple(args2)) if args1.len() == args2.len() => {
1328 let mut values = (DiagStyledString::normal("("), DiagStyledString::normal("("));
1329 let len = args1.len();
1330 for (i, (left, right)) in args1.iter().zip(args2).enumerate() {
1331 self.push_comma(&mut values.0, &mut values.1, i);
1332 self.recurse(left, right, &mut values);
1333 }
1334 if len == 1 {
1335 values.0.push_normal(",");
1337 values.1.push_normal(",");
1338 }
1339 values.0.push_normal(")");
1340 values.1.push_normal(")");
1341 values
1342 }
1343
1344 (ty::FnDef(did1, args1), ty::FnDef(did2, args2)) => {
1345 let args1 = args1.no_bound_vars().unwrap();
1346 let args2 = args2.no_bound_vars().unwrap();
1347
1348 let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1).skip_norm_wip();
1349 let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2).skip_norm_wip();
1350 self.cmp_fn_sig(sig1, Some((*did1, Some(args1))), sig2, Some((*did2, Some(args2))))
1351 }
1352
1353 (ty::FnDef(did1, args1), ty::FnPtr(sig_tys2, hdr2)) => {
1354 let args1 = args1.no_bound_vars().unwrap();
1355 let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1).skip_norm_wip();
1356 self.cmp_fn_sig(sig1, Some((*did1, Some(args1))), sig_tys2.with(*hdr2), None)
1357 }
1358
1359 (ty::FnPtr(sig_tys1, hdr1), ty::FnDef(did2, args2)) => {
1360 let args2 = args2.no_bound_vars().unwrap();
1361
1362 let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2).skip_norm_wip();
1363 self.cmp_fn_sig(sig_tys1.with(*hdr1), None, sig2, Some((*did2, Some(args2))))
1364 }
1365
1366 (ty::FnPtr(sig_tys1, hdr1), ty::FnPtr(sig_tys2, hdr2)) => {
1367 self.cmp_fn_sig(sig_tys1.with(*hdr1), None, sig_tys2.with(*hdr2), None)
1368 }
1369
1370 (ty::Alias(kind1, alias1), ty::Alias(kind2, alias2))
1371 if kind1 == kind2 && alias1 == alias2 && !self.tcx.sess.opts.verbose =>
1372 {
1373 let mut strs = (DiagStyledString::new(), DiagStyledString::new());
1374 strs.0.push_normal("_");
1375 strs.1.push_normal("_");
1376 strs
1377 }
1378
1379 (ty::Alias(kind1, alias1), ty::Alias(kind2, alias2)) if kind1 == kind2 => {
1380 let mut values = (DiagStyledString::new(), DiagStyledString::new());
1381 match (alias1.kind, alias2.kind) {
1382 (ty::Projection { def_id: def_id1 }, ty::Projection { def_id: def_id2 })
1383 if !self.tcx.is_impl_trait_in_trait(def_id1)
1386 && !self.tcx.is_impl_trait_in_trait(def_id2) =>
1387 {
1388 values.0.push_normal("<");
1390 values.1.push_normal("<");
1391 let (trait_ref1, args1) = alias1.trait_ref_and_own_args(self.tcx);
1392 let (trait_ref2, args2) = alias2.trait_ref_and_own_args(self.tcx);
1393 self.recurse(trait_ref1.self_ty(), trait_ref2.self_ty(), &mut values);
1394
1395 values.0.push_normal(" as ");
1396 values.1.push_normal(" as ");
1397 if trait_ref1.def_id == trait_ref2.def_id {
1398 if self.tcx.sess.opts.verbose {
1399 values
1400 .0
1401 .push_normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}",
trait_ref1.print_only_trait_name()))
})format!("{}", trait_ref1.print_only_trait_name()));
1402 values
1403 .1
1404 .push_normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}",
trait_ref2.print_only_trait_name()))
})format!("{}", trait_ref2.print_only_trait_name()));
1405 } else {
1406 {
let _guard = ForceTrimmedGuard::new();
{
values.0.push_normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}",
trait_ref1.print_only_trait_name()))
}));
values.1.push_normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}",
trait_ref2.print_only_trait_name()))
}));
}
}with_forced_trimmed_paths! {{
1407 values
1408 .0
1409 .push_normal(format!("{}", trait_ref1.print_only_trait_name()));
1410 values
1411 .1
1412 .push_normal(format!("{}", trait_ref2.print_only_trait_name()));
1413 }}
1414 }
1415 let args1 = &trait_ref1.args.as_slice()[1..];
1417 let args2 = &trait_ref2.args.as_slice()[1..];
1418 self.compare_generics(&mut values, args1, args2);
1419 } else {
1420 values
1421 .0
1422 .push_highlighted(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}",
trait_ref1.print_trait_sugared()))
})format!("{}", trait_ref1.print_trait_sugared()));
1423 values
1424 .1
1425 .push_highlighted(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}",
trait_ref2.print_trait_sugared()))
})format!("{}", trait_ref2.print_trait_sugared()));
1426 }
1427 values.0.push_normal(">::");
1428 values.1.push_normal(">::");
1429 let name1 = self.tcx.item_name(def_id1);
1430 let name2 = self.tcx.item_name(def_id2);
1431 if def_id1 == def_id2 {
1432 values.0.push_normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", name1))
})format!("{name1}"));
1433 values.1.push_normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", name2))
})format!("{name2}"));
1434 } else {
1435 values.0.push_highlighted(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", name1))
})format!("{name1}"));
1438 values.1.push_highlighted(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}", name2))
})format!("{name2}"));
1439 }
1440 self.compare_generics(&mut values, args1, args2);
1441 }
1442 _ => {
1443 self.maybe_highlight(t1, t2, &mut values, self.tcx);
1444 }
1445 }
1446 values
1447 }
1448
1449 _ => {
1450 let mut strs = (DiagStyledString::new(), DiagStyledString::new());
1451 self.maybe_highlight(t1, t2, &mut strs, self.tcx);
1452 strs
1453 }
1454 }
1455 }
1456
1457 {}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("note_type_err",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1466u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("cause")
}> =
::tracing::__macro_support::FieldName::new("cause");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("values")
}> =
::tracing::__macro_support::FieldName::new("values");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("terr")
}> =
::tracing::__macro_support::FieldName::new("terr");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("override_span")
}> =
::tracing::__macro_support::FieldName::new("override_span");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&values)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terr)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&override_span)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: () = loop {};
return __tracing_attr_fake_return;
}
{
let span = override_span.unwrap_or(cause.span);
if let TypeError::CyclicTy(_) = terr { values = None; }
struct OpaqueTypesVisitor<'tcx> {
types: FxIndexMap<TyCategory, FxIndexSet<Span>>,
expected: FxIndexMap<TyCategory, FxIndexSet<Span>>,
found: FxIndexMap<TyCategory, FxIndexSet<Span>>,
ignore_span: Span,
tcx: TyCtxt<'tcx>,
}
impl<'tcx> OpaqueTypesVisitor<'tcx> {
fn visit_expected_found(tcx: TyCtxt<'tcx>,
expected: impl TypeVisitable<TyCtxt<'tcx>>,
found: impl TypeVisitable<TyCtxt<'tcx>>, ignore_span: Span)
-> Self {
let mut types_visitor =
OpaqueTypesVisitor {
types: Default::default(),
expected: Default::default(),
found: Default::default(),
ignore_span,
tcx,
};
expected.visit_with(&mut types_visitor);
std::mem::swap(&mut types_visitor.expected,
&mut types_visitor.types);
found.visit_with(&mut types_visitor);
std::mem::swap(&mut types_visitor.found,
&mut types_visitor.types);
types_visitor
}
fn report(&self, err: &mut Diag<'_>) {
self.add_labels_for_types(err, "expected", &self.expected);
self.add_labels_for_types(err, "found", &self.found);
}
fn add_labels_for_types(&self, err: &mut Diag<'_>,
target: &str,
types: &FxIndexMap<TyCategory, FxIndexSet<Span>>) {
for (kind, values) in types.iter() {
let count = values.len();
for &sp in values {
err.span_label(sp,
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1} {2:#}{3}",
if count == 1 { "the " } else { "one of the " }, target,
kind, if count == 1 { "" } else { "s" }))
}));
}
}
}
}
impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for
OpaqueTypesVisitor<'tcx> {
fn visit_ty(&mut self, t: Ty<'tcx>) {
if let Some((kind, def_id)) =
TyCategory::from_ty(self.tcx, t) {
let span = self.tcx.def_span(def_id);
if !self.ignore_span.overlaps(span) &&
!span.is_desugaring(DesugaringKind::Async) {
self.types.entry(kind).or_default().insert(span);
}
}
t.super_visit_with(self)
}
}
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1577",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1577u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("note_type_err(diag={0:?})",
diag) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
enum Mismatch<'a> {
Variable(ty::error::ExpectedFound<Ty<'a>>),
Fixed(&'static str),
}
let (expected_found, exp_found, is_simple_error, values,
param_env) =
match values {
None => (None, Mismatch::Fixed("type"), false, None, None),
Some(ty::ParamEnvAnd { param_env, value: values }) => {
let values = self.deeply_resolve_ignoring_regions(values);
let (is_simple_error, exp_found) =
match values {
ValuePairs::Terms(ExpectedFound { expected, found }) => {
match (expected.kind(), found.kind()) {
(ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
let is_simple_err =
expected.is_simple_text() && found.is_simple_text();
OpaqueTypesVisitor::visit_expected_found(self.tcx, expected,
found, span).report(diag);
(is_simple_err,
Mismatch::Variable(ExpectedFound { expected, found }))
}
(ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
(false, Mismatch::Fixed("constant"))
}
_ => (false, Mismatch::Fixed("type")),
}
}
ValuePairs::PolySigs(ExpectedFound { expected, found }) => {
OpaqueTypesVisitor::visit_expected_found(self.tcx, expected,
found, span).report(diag);
(false, Mismatch::Fixed("signature"))
}
ValuePairs::TraitRefs(_) =>
(false, Mismatch::Fixed("trait")),
ValuePairs::Aliases(ExpectedFound { expected, .. }) => {
let def_id =
match expected.kind {
ty::AliasTermKind::ProjectionTy { def_id } |
ty::AliasTermKind::InherentTy { def_id } |
ty::AliasTermKind::OpaqueTy { def_id } |
ty::AliasTermKind::FreeTy { def_id } |
ty::AliasTermKind::AnonConst { def_id } |
ty::AliasTermKind::ProjectionConst { def_id } |
ty::AliasTermKind::FreeConst { def_id } |
ty::AliasTermKind::InherentConstSelf { def_id } |
ty::AliasTermKind::InherentConstImpl { def_id } => def_id,
};
(false, Mismatch::Fixed(self.tcx.def_descr(def_id)))
}
ValuePairs::Regions(_) =>
(false, Mismatch::Fixed("lifetime")),
ValuePairs::ExistentialTraitRef(_) => {
(false, Mismatch::Fixed("existential trait ref"))
}
ValuePairs::ExistentialProjection(_) => {
(false, Mismatch::Fixed("existential projection"))
}
};
let Some(vals) =
self.values_str(values, cause,
diag.long_ty_path()) else {
diag.downgrade_to_delayed_bug();
return;
};
(Some(vals), exp_found, is_simple_error, Some(values),
Some(param_env))
}
};
let mut label_or_note =
|span: MultiSpan, msg: Cow<'static, str>|
{
if !span.has_span_labels() && span.span_context().is_empty()
&&
((prefer_label && is_simple_error) ||
span.primary_spans() == diag.span.primary_spans()) {
for span in span.primary_spans() {
diag.span_label(*span, msg.clone());
}
} else { diag.span_note(span, msg); }
};
if let Some((secondary_span, secondary_msg,
swap_secondary_and_primary)) = secondary_span {
if swap_secondary_and_primary {
let terr =
if let Some(infer::ValuePairs::Terms(ExpectedFound {
expected, .. })) = values {
Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected this to be `{0}`",
expected))
}))
} else { terr.to_string(self.tcx) };
label_or_note(secondary_span, terr);
label_or_note(span.into(), secondary_msg);
} else {
label_or_note(span.into(), terr.to_string(self.tcx));
label_or_note(secondary_span, secondary_msg);
}
} else if let Some(values) = values &&
let Some((e, f)) = values.ty() &&
let TypeError::ArgumentSorts(..) | TypeError::Sorts(_) =
terr {
let e = self.tcx.erase_and_anonymize_regions(e);
let f = self.tcx.erase_and_anonymize_regions(f);
let expected =
{
let _guard = ForceTrimmedGuard::new();
e.sort_string(self.tcx)
};
let found =
{
let _guard = ForceTrimmedGuard::new();
f.sort_string(self.tcx)
};
if expected == found {
label_or_note(span.into(), terr.to_string(self.tcx));
} else {
label_or_note(span.into(),
Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1}",
expected, found))
})));
}
} else { label_or_note(span.into(), terr.to_string(self.tcx)); }
if let Some(param_env) = param_env {
self.note_field_shadowed_by_private_candidate_in_cause(diag,
cause, param_env);
}
if self.check_and_note_conflicting_crates(diag, terr) { return; }
if let Some((expected, found)) = expected_found {
let (expected_label, found_label, exp_found) =
match exp_found {
Mismatch::Variable(ef) =>
(ef.expected.prefix_string(self.tcx),
ef.found.prefix_string(self.tcx), Some(ef)),
Mismatch::Fixed(s) => (s.into(), s.into(), None),
};
enum Similar<'tcx> {
Adts {
expected: ty::AdtDef<'tcx>,
found: ty::AdtDef<'tcx>,
},
PrimitiveFound {
expected: ty::AdtDef<'tcx>,
found: Ty<'tcx>,
},
PrimitiveExpected {
expected: Ty<'tcx>,
found: ty::AdtDef<'tcx>,
},
}
let similarity =
|ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>|
{
if let ty::Adt(expected, _) = expected.kind() &&
let Some(primitive) = found.primitive_symbol() {
let path = self.tcx.def_path(expected.did()).data;
let name = path.last().unwrap().data.get_opt_name();
if name == Some(primitive) {
return Some(Similar::PrimitiveFound {
expected: *expected,
found,
});
}
} else if let Some(primitive) = expected.primitive_symbol()
&& let ty::Adt(found, _) = found.kind() {
let path = self.tcx.def_path(found.did()).data;
let name = path.last().unwrap().data.get_opt_name();
if name == Some(primitive) {
return Some(Similar::PrimitiveExpected {
expected,
found: *found,
});
}
} else if let ty::Adt(expected, _) = expected.kind() &&
let ty::Adt(found, _) = found.kind() {
if !expected.did().is_local() &&
expected.did().krate == found.did().krate {
return None;
}
let f_path = self.tcx.def_path(found.did()).data;
let e_path = self.tcx.def_path(expected.did()).data;
if let (Some(e_last), Some(f_last)) =
(e_path.last(), f_path.last()) && e_last == f_last {
return Some(Similar::Adts {
expected: *expected,
found: *found,
});
}
}
None
};
match terr {
TypeError::Sorts(values) if let Some(s) = similarity(values)
=> {
let diagnose_primitive =
|prim: Ty<'tcx>, shadow: Ty<'tcx>, defid: DefId,
diag: &mut Diag<'_>|
{
let name = shadow.sort_string(self.tcx);
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` and {1} have similar names, but are actually distinct types",
prim, name))
}));
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("one `{0}` is a primitive defined by the language",
prim))
}));
let def_span = self.tcx.def_span(defid);
let msg =
if defid.is_local() {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the other {0} is defined in the current crate",
name))
})
} else {
let crate_name = self.tcx.crate_name(defid.krate);
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the other {0} is defined in crate `{1}`",
name, crate_name))
})
};
diag.span_note(def_span, msg);
};
let diagnose_adts =
|expected_adt: ty::AdtDef<'tcx>,
found_adt: ty::AdtDef<'tcx>, diag: &mut Diag<'_>|
{
let found_name = values.found.sort_string(self.tcx);
let expected_name = values.expected.sort_string(self.tcx);
let found_defid = found_adt.did();
let expected_defid = expected_adt.did();
diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} and {1} have similar names, but are actually distinct types",
found_name, expected_name))
}));
for (defid, name) in
[(found_defid, found_name), (expected_defid, expected_name)]
{
let def_span = self.tcx.def_span(defid);
let msg =
if found_defid.is_local() && expected_defid.is_local() {
let module =
self.tcx.parent_module_from_def_id(defid.expect_local()).to_def_id();
let module_name =
self.tcx.def_path(module).to_string_no_crate_verbose();
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is defined in module `crate{1}` of the current crate",
name, module_name))
})
} else if defid.is_local() {
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is defined in the current crate",
name))
})
} else {
let crate_name = self.tcx.crate_name(defid.krate);
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} is defined in crate `{1}`",
name, crate_name))
})
};
diag.span_note(def_span, msg);
}
};
match s {
Similar::Adts { expected, found } =>
diagnose_adts(expected, found, diag),
Similar::PrimitiveFound { expected, found: prim } => {
diagnose_primitive(prim, values.expected, expected.did(),
diag)
}
Similar::PrimitiveExpected { expected: prim, found } => {
diagnose_primitive(prim, values.found, found.did(), diag)
}
}
}
TypeError::Sorts(values) => {
let extra =
expected == found &&
values.expected.sort_string(self.tcx) !=
values.found.sort_string(self.tcx);
let sort_string =
|ty: Ty<'tcx>|
match (extra, ty.kind()) {
(true,
ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, ..
})) => {
let sm = self.tcx.sess.source_map();
let pos =
sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
DiagStyledString::normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" (opaque type at <{0}:{1}:{2}>)",
sm.filename_for_diagnostics(&pos.file.name), pos.line,
pos.col.to_usize() + 1))
}))
}
(true,
&ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id },
.. })) if self.tcx.is_impl_trait_in_trait(def_id) => {
let sm = self.tcx.sess.source_map();
let pos =
sm.lookup_char_pos(self.tcx.def_span(def_id).lo());
DiagStyledString::normal(::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" (trait associated opaque type at <{0}:{1}:{2}>)",
sm.filename_for_diagnostics(&pos.file.name), pos.line,
pos.col.to_usize() + 1))
}))
}
(true, _) => {
let mut s = DiagStyledString::normal(" (");
s.push_highlighted(ty.sort_string(self.tcx));
s.push_normal(")");
s
}
(false, _) => DiagStyledString::normal(""),
};
if !(values.expected.is_simple_text() &&
values.found.is_simple_text()) ||
(exp_found.is_some_and(|ef|
{
if !ef.expected.is_ty_or_numeric_infer() {
ef.expected != values.expected
} else if !ef.found.is_ty_or_numeric_infer() {
ef.found != values.found
} else { false }
})) {
if let Some(ExpectedFound { found: found_ty, .. }) =
exp_found && !self.tcx.ty_is_opaque_future(found_ty) {
diag.note_expected_found_extra(&expected_label, expected,
&found_label, found, sort_string(values.expected),
sort_string(values.found));
}
}
}
_ => {
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1901",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1901u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("note_type_err: exp_found={0:?}, expected={1:?} found={2:?}",
exp_found, expected, found) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
if !is_simple_error || terr.must_include_note() {
diag.note_expected_found(&expected_label, expected,
&found_label, found);
if let Some(ty::Closure(_, args)) =
exp_found.map(|expected_type_found|
expected_type_found.found.kind()) {
diag.highlighted_note(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[StringPart::normal("closure has signature: `"),
StringPart::highlighted(self.tcx.signature_unclosure(args.as_closure().sig(),
rustc_hir::Safety::Safe).to_string()),
StringPart::normal("`")])));
}
}
}
}
}
let exp_found =
match exp_found {
Mismatch::Variable(exp_found) => Some(exp_found),
Mismatch::Fixed(_) => None,
};
let exp_found =
match terr {
ty::error::TypeError::Sorts(terr) if
exp_found.is_some_and(|ef| terr.found == ef.found) => {
Some(terr)
}
_ => exp_found,
};
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1941",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1941u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("exp_found {0:?} terr {1:?} cause.code {2:?}",
exp_found, terr, cause.code()) as
&dyn ::tracing::field::Value))])
});
} else { ; }
};
if let Some(exp_found) = exp_found {
let should_suggest_fixes =
if let ObligationCauseCode::Pattern { root_ty, .. } =
cause.code() {
self.same_type_modulo_infer(*root_ty, exp_found.expected)
} else { true };
if should_suggest_fixes &&
!#[allow(non_exhaustive_omitted_patterns)] match terr {
TypeError::RegionsInsufficientlyPolymorphic(..) => true,
_ => false,
} {
self.suggest_tuple_pattern(cause, &exp_found, diag);
self.suggest_accessing_field_where_appropriate(cause,
&exp_found, diag);
self.suggest_await_on_expect_found(cause, span, &exp_found,
diag);
self.suggest_function_pointers(cause, span, &exp_found,
terr, diag);
self.suggest_turning_stmt_into_expr(cause, &exp_found,
diag);
}
}
let body_owner_def_id =
(cause.body_def_id !=
CRATE_DEF_ID).then(|| cause.body_def_id.to_def_id());
self.note_and_explain_type_err(diag, terr, cause, span,
body_owner_def_id);
if let Some(exp_found) = exp_found &&
let exp_found = TypeError::Sorts(exp_found) &&
exp_found != terr {
self.note_and_explain_type_err(diag, exp_found, cause, span,
body_owner_def_id);
}
if let Some(ValuePairs::TraitRefs(exp_found)) = values &&
let ty::Closure(def_id, _) =
exp_found.expected.self_ty().kind() &&
let Some(def_id) = def_id.as_local() &&
terr.involves_regions() {
let span = self.tcx.def_span(def_id);
diag.span_note(span,
"this closure does not fulfill the lifetime requirements");
self.suggest_for_all_lifetime_closure(span,
self.tcx.hir_node_by_def_id(def_id), &exp_found, diag);
}
self.note_error_origin(diag, cause, exp_found, terr, param_env);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1995",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1995u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("diag")
}> =
::tracing::__macro_support::FieldName::new("diag");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&diag)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
}
}
}#[instrument(level = "debug", skip(self, diag, secondary_span, prefer_label))]
1467 pub fn note_type_err(
1468 &self,
1469 diag: &mut Diag<'_>,
1470 cause: &ObligationCause<'tcx>,
1471 secondary_span: Option<(MultiSpan, Cow<'static, str>, bool)>,
1472 mut values: Option<ty::ParamEnvAnd<'tcx, ValuePairs<'tcx>>>,
1473 terr: TypeError<'tcx>,
1474 prefer_label: bool,
1475 override_span: Option<Span>,
1476 ) {
1477 let span = override_span.unwrap_or(cause.span);
1482 if let TypeError::CyclicTy(_) = terr {
1485 values = None;
1486 }
1487 struct OpaqueTypesVisitor<'tcx> {
1488 types: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1489 expected: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1490 found: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1491 ignore_span: Span,
1492 tcx: TyCtxt<'tcx>,
1493 }
1494
1495 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1496 fn visit_expected_found(
1497 tcx: TyCtxt<'tcx>,
1498 expected: impl TypeVisitable<TyCtxt<'tcx>>,
1499 found: impl TypeVisitable<TyCtxt<'tcx>>,
1500 ignore_span: Span,
1501 ) -> Self {
1502 let mut types_visitor = OpaqueTypesVisitor {
1503 types: Default::default(),
1504 expected: Default::default(),
1505 found: Default::default(),
1506 ignore_span,
1507 tcx,
1508 };
1509 expected.visit_with(&mut types_visitor);
1513 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1514 found.visit_with(&mut types_visitor);
1515 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1516 types_visitor
1517 }
1518
1519 fn report(&self, err: &mut Diag<'_>) {
1520 self.add_labels_for_types(err, "expected", &self.expected);
1521 self.add_labels_for_types(err, "found", &self.found);
1522 }
1523
1524 fn add_labels_for_types(
1525 &self,
1526 err: &mut Diag<'_>,
1527 target: &str,
1528 types: &FxIndexMap<TyCategory, FxIndexSet<Span>>,
1529 ) {
1530 for (kind, values) in types.iter() {
1531 let count = values.len();
1532 for &sp in values {
1533 err.span_label(
1534 sp,
1535 format!(
1536 "{}{} {:#}{}",
1537 if count == 1 { "the " } else { "one of the " },
1538 target,
1539 kind,
1540 pluralize!(count),
1541 ),
1542 );
1543 }
1544 }
1545 }
1546 }
1547
1548 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypesVisitor<'tcx> {
1549 fn visit_ty(&mut self, t: Ty<'tcx>) {
1550 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1551 let span = self.tcx.def_span(def_id);
1552 if !self.ignore_span.overlaps(span)
1568 && !span.is_desugaring(DesugaringKind::Async)
1569 {
1570 self.types.entry(kind).or_default().insert(span);
1571 }
1572 }
1573 t.super_visit_with(self)
1574 }
1575 }
1576
1577 debug!("note_type_err(diag={:?})", diag);
1578 enum Mismatch<'a> {
1579 Variable(ty::error::ExpectedFound<Ty<'a>>),
1580 Fixed(&'static str),
1581 }
1582 let (expected_found, exp_found, is_simple_error, values, param_env) = match values {
1583 None => (None, Mismatch::Fixed("type"), false, None, None),
1584 Some(ty::ParamEnvAnd { param_env, value: values }) => {
1585 let values = self.deeply_resolve_ignoring_regions(values);
1586 let (is_simple_error, exp_found) = match values {
1587 ValuePairs::Terms(ExpectedFound { expected, found }) => {
1588 match (expected.kind(), found.kind()) {
1589 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
1590 let is_simple_err =
1591 expected.is_simple_text() && found.is_simple_text();
1592 OpaqueTypesVisitor::visit_expected_found(
1593 self.tcx, expected, found, span,
1594 )
1595 .report(diag);
1596
1597 (
1598 is_simple_err,
1599 Mismatch::Variable(ExpectedFound { expected, found }),
1600 )
1601 }
1602 (ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
1603 (false, Mismatch::Fixed("constant"))
1604 }
1605 _ => (false, Mismatch::Fixed("type")),
1606 }
1607 }
1608 ValuePairs::PolySigs(ExpectedFound { expected, found }) => {
1609 OpaqueTypesVisitor::visit_expected_found(self.tcx, expected, found, span)
1610 .report(diag);
1611 (false, Mismatch::Fixed("signature"))
1612 }
1613 ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed("trait")),
1614 ValuePairs::Aliases(ExpectedFound { expected, .. }) => {
1615 let def_id = match expected.kind {
1616 ty::AliasTermKind::ProjectionTy { def_id }
1617 | ty::AliasTermKind::InherentTy { def_id }
1618 | ty::AliasTermKind::OpaqueTy { def_id }
1619 | ty::AliasTermKind::FreeTy { def_id }
1620 | ty::AliasTermKind::AnonConst { def_id }
1621 | ty::AliasTermKind::ProjectionConst { def_id }
1622 | ty::AliasTermKind::FreeConst { def_id }
1623 | ty::AliasTermKind::InherentConstSelf { def_id }
1624 | ty::AliasTermKind::InherentConstImpl { def_id } => def_id,
1625 };
1626 (false, Mismatch::Fixed(self.tcx.def_descr(def_id)))
1627 }
1628 ValuePairs::Regions(_) => (false, Mismatch::Fixed("lifetime")),
1629 ValuePairs::ExistentialTraitRef(_) => {
1630 (false, Mismatch::Fixed("existential trait ref"))
1631 }
1632 ValuePairs::ExistentialProjection(_) => {
1633 (false, Mismatch::Fixed("existential projection"))
1634 }
1635 };
1636 let Some(vals) = self.values_str(values, cause, diag.long_ty_path()) else {
1637 diag.downgrade_to_delayed_bug();
1641 return;
1642 };
1643 (Some(vals), exp_found, is_simple_error, Some(values), Some(param_env))
1644 }
1645 };
1646
1647 let mut label_or_note = |span: MultiSpan, msg: Cow<'static, str>| {
1648 if !span.has_span_labels()
1649 && span.span_context().is_empty()
1650 && ((prefer_label && is_simple_error)
1651 || span.primary_spans() == diag.span.primary_spans())
1652 {
1653 for span in span.primary_spans() {
1654 diag.span_label(*span, msg.clone());
1655 }
1656 } else {
1657 diag.span_note(span, msg);
1658 }
1659 };
1660 if let Some((secondary_span, secondary_msg, swap_secondary_and_primary)) = secondary_span {
1661 if swap_secondary_and_primary {
1662 let terr = if let Some(infer::ValuePairs::Terms(ExpectedFound {
1663 expected, ..
1664 })) = values
1665 {
1666 Cow::from(format!("expected this to be `{expected}`"))
1667 } else {
1668 terr.to_string(self.tcx)
1669 };
1670 label_or_note(secondary_span, terr);
1671 label_or_note(span.into(), secondary_msg);
1672 } else {
1673 label_or_note(span.into(), terr.to_string(self.tcx));
1674 label_or_note(secondary_span, secondary_msg);
1675 }
1676 } else if let Some(values) = values
1677 && let Some((e, f)) = values.ty()
1678 && let TypeError::ArgumentSorts(..) | TypeError::Sorts(_) = terr
1679 {
1680 let e = self.tcx.erase_and_anonymize_regions(e);
1681 let f = self.tcx.erase_and_anonymize_regions(f);
1682 let expected = with_forced_trimmed_paths!(e.sort_string(self.tcx));
1683 let found = with_forced_trimmed_paths!(f.sort_string(self.tcx));
1684 if expected == found {
1685 label_or_note(span.into(), terr.to_string(self.tcx));
1686 } else {
1687 label_or_note(
1688 span.into(),
1689 Cow::from(format!("expected {expected}, found {found}")),
1690 );
1691 }
1692 } else {
1693 label_or_note(span.into(), terr.to_string(self.tcx));
1694 }
1695
1696 if let Some(param_env) = param_env {
1697 self.note_field_shadowed_by_private_candidate_in_cause(diag, cause, param_env);
1698 }
1699
1700 if self.check_and_note_conflicting_crates(diag, terr) {
1701 return;
1702 }
1703
1704 if let Some((expected, found)) = expected_found {
1705 let (expected_label, found_label, exp_found) = match exp_found {
1706 Mismatch::Variable(ef) => (
1707 ef.expected.prefix_string(self.tcx),
1708 ef.found.prefix_string(self.tcx),
1709 Some(ef),
1710 ),
1711 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1712 };
1713
1714 enum Similar<'tcx> {
1715 Adts { expected: ty::AdtDef<'tcx>, found: ty::AdtDef<'tcx> },
1716 PrimitiveFound { expected: ty::AdtDef<'tcx>, found: Ty<'tcx> },
1717 PrimitiveExpected { expected: Ty<'tcx>, found: ty::AdtDef<'tcx> },
1718 }
1719
1720 let similarity = |ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>| {
1721 if let ty::Adt(expected, _) = expected.kind()
1722 && let Some(primitive) = found.primitive_symbol()
1723 {
1724 let path = self.tcx.def_path(expected.did()).data;
1725 let name = path.last().unwrap().data.get_opt_name();
1726 if name == Some(primitive) {
1727 return Some(Similar::PrimitiveFound { expected: *expected, found });
1728 }
1729 } else if let Some(primitive) = expected.primitive_symbol()
1730 && let ty::Adt(found, _) = found.kind()
1731 {
1732 let path = self.tcx.def_path(found.did()).data;
1733 let name = path.last().unwrap().data.get_opt_name();
1734 if name == Some(primitive) {
1735 return Some(Similar::PrimitiveExpected { expected, found: *found });
1736 }
1737 } else if let ty::Adt(expected, _) = expected.kind()
1738 && let ty::Adt(found, _) = found.kind()
1739 {
1740 if !expected.did().is_local() && expected.did().krate == found.did().krate {
1741 return None;
1745 }
1746 let f_path = self.tcx.def_path(found.did()).data;
1747 let e_path = self.tcx.def_path(expected.did()).data;
1748
1749 if let (Some(e_last), Some(f_last)) = (e_path.last(), f_path.last())
1750 && e_last == f_last
1751 {
1752 return Some(Similar::Adts { expected: *expected, found: *found });
1753 }
1754 }
1755 None
1756 };
1757
1758 match terr {
1759 TypeError::Sorts(values) if let Some(s) = similarity(values) => {
1761 let diagnose_primitive =
1762 |prim: Ty<'tcx>, shadow: Ty<'tcx>, defid: DefId, diag: &mut Diag<'_>| {
1763 let name = shadow.sort_string(self.tcx);
1764 diag.note(format!(
1765 "`{prim}` and {name} have similar names, but are actually distinct types"
1766 ));
1767 diag.note(format!(
1768 "one `{prim}` is a primitive defined by the language",
1769 ));
1770 let def_span = self.tcx.def_span(defid);
1771 let msg = if defid.is_local() {
1772 format!("the other {name} is defined in the current crate")
1773 } else {
1774 let crate_name = self.tcx.crate_name(defid.krate);
1775 format!("the other {name} is defined in crate `{crate_name}`")
1776 };
1777 diag.span_note(def_span, msg);
1778 };
1779
1780 let diagnose_adts =
1781 |expected_adt: ty::AdtDef<'tcx>,
1782 found_adt: ty::AdtDef<'tcx>,
1783 diag: &mut Diag<'_>| {
1784 let found_name = values.found.sort_string(self.tcx);
1785 let expected_name = values.expected.sort_string(self.tcx);
1786
1787 let found_defid = found_adt.did();
1788 let expected_defid = expected_adt.did();
1789
1790 diag.note(format!("{found_name} and {expected_name} have similar names, but are actually distinct types"));
1791 for (defid, name) in
1792 [(found_defid, found_name), (expected_defid, expected_name)]
1793 {
1794 let def_span = self.tcx.def_span(defid);
1795
1796 let msg = if found_defid.is_local() && expected_defid.is_local() {
1797 let module = self
1798 .tcx
1799 .parent_module_from_def_id(defid.expect_local())
1800 .to_def_id();
1801 let module_name =
1802 self.tcx.def_path(module).to_string_no_crate_verbose();
1803 format!(
1804 "{name} is defined in module `crate{module_name}` of the current crate"
1805 )
1806 } else if defid.is_local() {
1807 format!("{name} is defined in the current crate")
1808 } else {
1809 let crate_name = self.tcx.crate_name(defid.krate);
1810 format!("{name} is defined in crate `{crate_name}`")
1811 };
1812 diag.span_note(def_span, msg);
1813 }
1814 };
1815
1816 match s {
1817 Similar::Adts { expected, found } => diagnose_adts(expected, found, diag),
1818 Similar::PrimitiveFound { expected, found: prim } => {
1819 diagnose_primitive(prim, values.expected, expected.did(), diag)
1820 }
1821 Similar::PrimitiveExpected { expected: prim, found } => {
1822 diagnose_primitive(prim, values.found, found.did(), diag)
1823 }
1824 }
1825 }
1826 TypeError::Sorts(values) => {
1827 let extra = expected == found
1828 && values.expected.sort_string(self.tcx)
1832 != values.found.sort_string(self.tcx);
1833 let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1834 (true, ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. })) => {
1835 let sm = self.tcx.sess.source_map();
1836 let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1837 DiagStyledString::normal(format!(
1838 " (opaque type at <{}:{}:{}>)",
1839 sm.filename_for_diagnostics(&pos.file.name),
1840 pos.line,
1841 pos.col.to_usize() + 1,
1842 ))
1843 }
1844 (
1845 true,
1846 &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, .. }),
1847 ) if self.tcx.is_impl_trait_in_trait(def_id) => {
1848 let sm = self.tcx.sess.source_map();
1849 let pos = sm.lookup_char_pos(self.tcx.def_span(def_id).lo());
1850 DiagStyledString::normal(format!(
1851 " (trait associated opaque type at <{}:{}:{}>)",
1852 sm.filename_for_diagnostics(&pos.file.name),
1853 pos.line,
1854 pos.col.to_usize() + 1,
1855 ))
1856 }
1857 (true, _) => {
1858 let mut s = DiagStyledString::normal(" (");
1859 s.push_highlighted(ty.sort_string(self.tcx));
1860 s.push_normal(")");
1861 s
1862 }
1863 (false, _) => DiagStyledString::normal(""),
1864 };
1865 if !(values.expected.is_simple_text() && values.found.is_simple_text())
1866 || (exp_found.is_some_and(|ef| {
1867 if !ef.expected.is_ty_or_numeric_infer() {
1872 ef.expected != values.expected
1873 } else if !ef.found.is_ty_or_numeric_infer() {
1874 ef.found != values.found
1875 } else {
1876 false
1877 }
1878 }))
1879 {
1880 if let Some(ExpectedFound { found: found_ty, .. }) = exp_found
1881 && !self.tcx.ty_is_opaque_future(found_ty)
1882 {
1883 diag.note_expected_found_extra(
1890 &expected_label,
1891 expected,
1892 &found_label,
1893 found,
1894 sort_string(values.expected),
1895 sort_string(values.found),
1896 );
1897 }
1898 }
1899 }
1900 _ => {
1901 debug!(
1902 "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1903 exp_found, expected, found
1904 );
1905 if !is_simple_error || terr.must_include_note() {
1906 diag.note_expected_found(&expected_label, expected, &found_label, found);
1907
1908 if let Some(ty::Closure(_, args)) =
1909 exp_found.map(|expected_type_found| expected_type_found.found.kind())
1910 {
1911 diag.highlighted_note(vec![
1912 StringPart::normal("closure has signature: `"),
1913 StringPart::highlighted(
1914 self.tcx
1915 .signature_unclosure(
1916 args.as_closure().sig(),
1917 rustc_hir::Safety::Safe,
1918 )
1919 .to_string(),
1920 ),
1921 StringPart::normal("`"),
1922 ]);
1923 }
1924 }
1925 }
1926 }
1927 }
1928 let exp_found = match exp_found {
1929 Mismatch::Variable(exp_found) => Some(exp_found),
1930 Mismatch::Fixed(_) => None,
1931 };
1932 let exp_found = match terr {
1933 ty::error::TypeError::Sorts(terr)
1935 if exp_found.is_some_and(|ef| terr.found == ef.found) =>
1936 {
1937 Some(terr)
1938 }
1939 _ => exp_found,
1940 };
1941 debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
1942 if let Some(exp_found) = exp_found {
1943 let should_suggest_fixes =
1944 if let ObligationCauseCode::Pattern { root_ty, .. } = cause.code() {
1945 self.same_type_modulo_infer(*root_ty, exp_found.expected)
1948 } else {
1949 true
1950 };
1951
1952 if should_suggest_fixes
1956 && !matches!(terr, TypeError::RegionsInsufficientlyPolymorphic(..))
1957 {
1958 self.suggest_tuple_pattern(cause, &exp_found, diag);
1959 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1960 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1961 self.suggest_function_pointers(cause, span, &exp_found, terr, diag);
1962 self.suggest_turning_stmt_into_expr(cause, &exp_found, diag);
1963 }
1964 }
1965
1966 let body_owner_def_id =
1967 (cause.body_def_id != CRATE_DEF_ID).then(|| cause.body_def_id.to_def_id());
1968 self.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id);
1969 if let Some(exp_found) = exp_found
1970 && let exp_found = TypeError::Sorts(exp_found)
1971 && exp_found != terr
1972 {
1973 self.note_and_explain_type_err(diag, exp_found, cause, span, body_owner_def_id);
1974 }
1975
1976 if let Some(ValuePairs::TraitRefs(exp_found)) = values
1977 && let ty::Closure(def_id, _) = exp_found.expected.self_ty().kind()
1978 && let Some(def_id) = def_id.as_local()
1979 && terr.involves_regions()
1980 {
1981 let span = self.tcx.def_span(def_id);
1982 diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1983 self.suggest_for_all_lifetime_closure(
1984 span,
1985 self.tcx.hir_node_by_def_id(def_id),
1986 &exp_found,
1987 diag,
1988 );
1989 }
1990
1991 self.note_error_origin(diag, cause, exp_found, terr, param_env);
1994
1995 debug!(?diag);
1996 }
1997
1998 pub(crate) fn type_error_additional_suggestions(
1999 &self,
2000 trace: &TypeTrace<'tcx>,
2001 terr: TypeError<'tcx>,
2002 long_ty_path: &mut Option<PathBuf>,
2003 ) -> Vec<TypeErrorAdditionalDiags> {
2004 let mut suggestions = Vec::new();
2005 let span = trace.cause.span;
2006 let values = self.deeply_resolve_ignoring_regions(trace.values);
2007 if let Some((expected, found)) = values.ty() {
2008 match (expected.kind(), found.kind()) {
2009 (ty::Tuple(_), ty::Tuple(_)) => {}
2010 (ty::Tuple(fields), _) => {
2014 suggestions.extend(self.suggest_wrap_to_build_a_tuple(span, found, fields))
2015 }
2016 (ty::Uint(ty::UintTy::U8), ty::Char) => {
2020 if let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span)
2021 && let Some(code) = code.strip_circumfix('\'', '\'')
2022 && !code.starts_with("\\u")
2024 && code.chars().next().is_some_and(|c| c.is_ascii())
2026 {
2027 suggestions.push(TypeErrorAdditionalDiags::MeantByteLiteral {
2028 span,
2029 code: escape_literal(code),
2030 })
2031 }
2032 }
2033 (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
2037 if let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span)
2038 && let Some(code) = code.strip_circumfix('"', '"')
2039 && code.chars().count() == 1
2040 {
2041 suggestions.push(TypeErrorAdditionalDiags::MeantCharLiteral {
2042 span,
2043 code: escape_literal(code),
2044 })
2045 }
2046 }
2047 (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
2050 if let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span)
2051 && code.starts_with("'")
2052 && code.ends_with("'")
2053 {
2054 suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral {
2055 start: span.with_hi(span.lo() + BytePos(1)),
2056 end: span.with_lo(span.hi() - BytePos(1)),
2057 });
2058 }
2059 }
2060 (ty::Bool, ty::Tuple(list)) => {
2063 if list.len() == 0 {
2064 suggestions.extend(self.suggest_let_for_letchains(&trace.cause, span));
2065 }
2066 }
2067 (ty::Array(_, _), ty::Array(_, _)) => {
2068 suggestions.extend(self.suggest_specify_actual_length(terr, trace, span))
2069 }
2070 _ => {}
2071 }
2072 }
2073 let code = trace.cause.code();
2074 if let &(ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
2075 source, ..
2076 })
2077 | ObligationCauseCode::BlockTailExpression(.., source)) = code
2078 && let hir::MatchSource::TryDesugar(_) = source
2079 && let Some((expected_ty, found_ty)) =
2080 self.values_str(trace.values, &trace.cause, long_ty_path)
2081 {
2082 suggestions.push(TypeErrorAdditionalDiags::TryCannotConvert {
2083 found: found_ty.content(),
2084 expected: expected_ty.content(),
2085 });
2086 }
2087 suggestions
2088 }
2089
2090 fn suggest_specify_actual_length(
2091 &self,
2092 terr: TypeError<'tcx>,
2093 trace: &TypeTrace<'tcx>,
2094 span: Span,
2095 ) -> Option<TypeErrorAdditionalDiags> {
2096 let TypeError::ArraySize(sz) = terr else {
2097 return None;
2098 };
2099 let tykind = match self.tcx.hir_node_by_def_id(trace.cause.body_def_id) {
2100 hir::Node::Item(hir::Item {
2101 kind: hir::ItemKind::Fn { body: body_id, .. }, ..
2102 }) => {
2103 let body = self.tcx.hir_body(*body_id);
2104 struct LetVisitor {
2105 span: Span,
2106 }
2107 impl<'v> Visitor<'v> for LetVisitor {
2108 type Result = ControlFlow<&'v hir::TyKind<'v>>;
2109 fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
2110 if let hir::Stmt {
2113 kind:
2114 hir::StmtKind::Let(hir::LetStmt {
2115 init: Some(hir::Expr { span: init_span, .. }),
2116 ty: Some(array_ty),
2117 ..
2118 }),
2119 ..
2120 } = s
2121 && init_span == &self.span
2122 {
2123 ControlFlow::Break(&array_ty.peel_refs().kind)
2124 } else {
2125 ControlFlow::Continue(())
2126 }
2127 }
2128 }
2129 LetVisitor { span }.visit_body(body).break_value()
2130 }
2131 hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(_, _, ty, _), .. }) => {
2132 Some(&ty.peel_refs().kind)
2133 }
2134 _ => None,
2135 };
2136 if let Some(tykind) = tykind
2137 && let hir::TyKind::Array(_, length_arg) = tykind
2138 && let Some(length_val) = sz.found.try_to_target_usize(self.tcx)
2139 {
2140 Some(TypeErrorAdditionalDiags::ConsiderSpecifyingLength {
2141 span: length_arg.span,
2142 length: length_val,
2143 })
2144 } else {
2145 None
2146 }
2147 }
2148
2149 fn check_on_type_error_attribute(
2150 &self,
2151 expected_ty: Ty<'tcx>,
2152 found_ty: Ty<'tcx>,
2153 ) -> ThinVec<String> {
2154 let mut seen = FxHashSet::default();
2155 let mut unique_notes: ThinVec<String> = ThinVec::new();
2156
2157 if let ty::Adt(item_def, args) = found_ty.kind() {
2159 if let Some(Some(directive)) =
2160 {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(item_def.did(),
&self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(OnTypeError { directive,
.. }) => {
break 'done Some(directive);
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.tcx, item_def.did(), OnTypeError { directive, .. } => directive)
2161 {
2162 let notes = self.format_on_type_error_notes(
2163 directive,
2164 args,
2165 item_def.clone(),
2166 expected_ty,
2167 found_ty,
2168 );
2169
2170 for note in notes {
2171 if seen.insert(note.clone()) {
2172 unique_notes.push(note);
2173 }
2174 }
2175 }
2176 }
2177
2178 if let ty::Adt(item_def, args) = expected_ty.kind() {
2180 if let Some(Some(directive)) =
2181 {
{
'done:
{
for i in
::rustc_attr_ir::HasAttrs::get_attrs(item_def.did(),
&self.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(OnTypeError { directive,
.. }) => {
break 'done Some(directive);
}
::rustc_attr_ir::Attribute::Tool { .. } |
::rustc_attr_ir::Attribute::DeriveHelper(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.tcx, item_def.did(), OnTypeError { directive, .. } => directive)
2182 {
2183 let notes = self.format_on_type_error_notes(
2184 directive,
2185 args,
2186 item_def.clone(),
2187 expected_ty,
2188 found_ty,
2189 );
2190
2191 for note in notes {
2192 if seen.insert(note.clone()) {
2193 unique_notes.push(note);
2194 }
2195 }
2196 }
2197 }
2198
2199 unique_notes
2200 }
2201
2202 fn format_on_type_error_notes(
2203 &self,
2204 directive: &Directive,
2205 args: &ty::GenericArgs<'tcx>,
2206 item_def: ty::AdtDef<'tcx>,
2207 expected_ty: Ty<'tcx>,
2208 found_ty: Ty<'tcx>,
2209 ) -> ThinVec<String> {
2210 let item_name = self.tcx.item_name(item_def.did()).to_string();
2211 let generic_args: Vec<_> = self
2212 .tcx
2213 .generics_of(item_def.did())
2214 .own_params
2215 .iter()
2216 .filter_map(|param| Some((param.name, args[param.index as usize].to_string())))
2217 .collect();
2218
2219 let format_args = FormatArgs {
2220 this: item_name,
2221 generic_args,
2222 found: found_ty.to_string(),
2223 expected: expected_ty.to_string(),
2224 ..
2225 };
2226 let CustomDiagnostic { notes, .. } = directive.eval(None, &format_args);
2227
2228 notes.into()
2229 }
2230
2231 pub fn report_and_explain_type_error(
2232 &self,
2233 mut trace: TypeTrace<'tcx>,
2234 param_env: ty::ParamEnv<'tcx>,
2235 terr: TypeError<'tcx>,
2236 ) -> Diag<'a> {
2237 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:2237",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/c82ce15637153c025d29abbaff6035a177361788/compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(2237u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("report_and_explain_type_error(trace={0:?}, terr={1:?})",
trace, terr) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
2238
2239 let span = trace.cause.span;
2240 let mut path = None;
2241
2242 self.simplify_pin_macro_arg_ty_mismatch(&mut trace);
2243
2244 let on_type_error_notes = if let Some((expected_ty, found_ty)) = trace.values.ty() {
2246 self.check_on_type_error_attribute(expected_ty, found_ty)
2247 } else {
2248 ThinVec::new()
2249 };
2250
2251 let failure_code = trace.cause.as_failure_code_diag(
2252 terr,
2253 span,
2254 self.type_error_additional_suggestions(&trace, terr, &mut path),
2255 );
2256 let mut diag = self.dcx().create_err(failure_code);
2257 *diag.long_ty_path() = path;
2258
2259 for note in on_type_error_notes {
2261 diag.note(note);
2262 }
2263
2264 self.note_type_err(
2265 &mut diag,
2266 &trace.cause,
2267 None,
2268 Some(param_env.and(trace.values)),
2269 terr,
2270 false,
2271 None,
2272 );
2273 diag
2274 }
2275
2276 fn simplify_pin_macro_arg_ty_mismatch(&self, trace: &mut TypeTrace<'tcx>) {
2280 if let Some((expected_ty, found_ty)) = trace.values.ty()
2283 && let ty::Ref(_, expected_ty_kind_inside_mut, Mutability::Mut) = expected_ty.kind()
2284 && let ty::Adt(expected_adt, expected_generics) = expected_ty_kind_inside_mut.kind()
2285 && self.tcx.is_diagnostic_item(sym::PinMacroHelper, expected_adt.did())
2286 && let ty::Ref(_, found_ty_kind_inside_mut, Mutability::Mut) = found_ty.kind()
2287 && let ty::Adt(found_adt, found_generics) = found_ty_kind_inside_mut.kind()
2288 && self.tcx.is_diagnostic_item(sym::PinMacroHelper, found_adt.did())
2289 {
2290 let [expected_generic] = expected_generics
2291 .as_slice()
2292 .try_into()
2293 .expect("PinMacroHelper should only have one generic");
2294 let [found_generic] = found_generics
2295 .as_slice()
2296 .try_into()
2297 .expect("PinMacroHelper should only have one generic");
2298 let expected_ty_inner =
2299 expected_generic.as_type().expect("PinMacroHelper should have a generic type");
2300 let found_ty_inner =
2301 found_generic.as_type().expect("PinMacroHelper should have a generic type");
2302 trace.values = ValuePairs::Terms(ExpectedFound::new(
2303 expected_ty_inner.into(),
2304 found_ty_inner.into(),
2305 ));
2306 }
2307 }
2308
2309 fn suggest_wrap_to_build_a_tuple(
2310 &self,
2311 span: Span,
2312 found: Ty<'tcx>,
2313 expected_fields: &List<Ty<'tcx>>,
2314 ) -> Option<TypeErrorAdditionalDiags> {
2315 let [expected_tup_elem] = expected_fields[..] else { return None };
2316
2317 if !self.same_type_modulo_infer(expected_tup_elem, found) {
2318 return None;
2319 }
2320
2321 let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span) else { return None };
2322
2323 let sugg = if code.starts_with('(') && code.ends_with(')') {
2324 let before_close = span.hi() - BytePos::from_u32(1);
2325 TypeErrorAdditionalDiags::TupleOnlyComma {
2326 span: span.with_hi(before_close).shrink_to_hi(),
2327 }
2328 } else {
2329 TypeErrorAdditionalDiags::TupleAlsoParentheses {
2330 span_low: span.shrink_to_lo(),
2331 span_high: span.shrink_to_hi(),
2332 }
2333 };
2334 Some(sugg)
2335 }
2336
2337 fn values_str(
2338 &self,
2339 values: ValuePairs<'tcx>,
2340 cause: &ObligationCause<'tcx>,
2341 long_ty_path: &mut Option<PathBuf>,
2342 ) -> Option<(DiagStyledString, DiagStyledString)> {
2343 match values {
2344 ValuePairs::Regions(exp_found) => self.expected_found_str(exp_found),
2345 ValuePairs::Terms(exp_found) => self.expected_found_str_term(exp_found, long_ty_path),
2346 ValuePairs::Aliases(exp_found) => self.expected_found_str(exp_found),
2347 ValuePairs::ExistentialTraitRef(exp_found) => self.expected_found_str(exp_found),
2348 ValuePairs::ExistentialProjection(exp_found) => self.expected_found_str(exp_found),
2349 ValuePairs::TraitRefs(exp_found) => {
2350 let pretty_exp_found = ty::error::ExpectedFound {
2351 expected: exp_found.expected.print_trait_sugared(),
2352 found: exp_found.found.print_trait_sugared(),
2353 };
2354 match self.expected_found_str(pretty_exp_found) {
2355 Some((expected, found)) if expected == found => {
2356 self.expected_found_str(exp_found)
2357 }
2358 ret => ret,
2359 }
2360 }
2361 ValuePairs::PolySigs(exp_found) => {
2362 let exp_found = self.deeply_resolve_ignoring_regions(exp_found);
2363 if exp_found.references_error() {
2364 return None;
2365 }
2366 let (fn_def1, fn_def2) = if let ObligationCauseCode::CompareImplItem {
2367 impl_item_def_id,
2368 trait_item_def_id,
2369 ..
2370 } = *cause.code()
2371 {
2372 (Some((trait_item_def_id, None)), Some((impl_item_def_id.to_def_id(), None)))
2373 } else {
2374 (None, None)
2375 };
2376
2377 Some(self.cmp_fn_sig(exp_found.expected, fn_def1, exp_found.found, fn_def2))
2378 }
2379 }
2380 }
2381
2382 fn expected_found_str_term(
2383 &self,
2384 exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2385 long_ty_path: &mut Option<PathBuf>,
2386 ) -> Option<(DiagStyledString, DiagStyledString)> {
2387 let exp_found = self.deeply_resolve_ignoring_regions(exp_found);
2388 if exp_found.references_error() {
2389 return None;
2390 }
2391
2392 Some(match (exp_found.expected.kind(), exp_found.found.kind()) {
2393 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
2394 let (mut exp, mut fnd) = self.cmp(expected, found);
2395 let len = self.tcx.sess.diagnostic_width();
2399 let exp_s = exp.content();
2400 let fnd_s = fnd.content();
2401 if !self.tcx.sess.opts.verbose
2402 && self.tcx.sess.opts.unstable_opts.write_long_types_to_disk
2403 {
2404 if exp_s.len() > len && fnd_s.len() > len {
2407 let exp_short = self.tcx.short_string(expected, long_ty_path);
2408 let fnd_short = self.tcx.short_string(found, long_ty_path);
2409 exp.shorten();
2413 fnd.shorten();
2414 if exp_short != fnd_short {
2415 if exp.0.len() <= 1 {
2418 exp = DiagStyledString::highlighted(exp_short);
2421 }
2422 if fnd.0.len() <= 1 {
2423 fnd = DiagStyledString::highlighted(fnd_short);
2426 }
2427 }
2428 } else {
2429 if exp_s.len() > len {
2430 exp.shorten();
2431 let exp_short = self.tcx.short_string(expected, long_ty_path);
2432 if exp.0.len() <= 1 {
2433 exp = DiagStyledString::highlighted(exp_short);
2434 }
2435 }
2436 if fnd_s.len() > len {
2437 fnd.shorten();
2438 let fnd_short = self.tcx.short_string(found, long_ty_path);
2439 if fnd.0.len() <= 1 {
2440 fnd = DiagStyledString::highlighted(fnd_short);
2441 }
2442 }
2443 }
2444 }
2445 (exp, fnd)
2446 }
2447 _ => (
2448 DiagStyledString::highlighted(exp_found.expected.to_string()),
2449 DiagStyledString::highlighted(exp_found.found.to_string()),
2450 ),
2451 })
2452 }
2453
2454 fn expected_found_str<T: fmt::Display + TypeFoldable<TyCtxt<'tcx>>>(
2456 &self,
2457 exp_found: ty::error::ExpectedFound<T>,
2458 ) -> Option<(DiagStyledString, DiagStyledString)> {
2459 let exp_found = self.deeply_resolve_ignoring_regions(exp_found);
2460 if exp_found.references_error() {
2461 return None;
2462 }
2463
2464 Some((
2465 DiagStyledString::highlighted(exp_found.expected.to_string()),
2466 DiagStyledString::highlighted(exp_found.found.to_string()),
2467 ))
2468 }
2469
2470 pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2474 span.is_desugaring(DesugaringKind::QuestionMark)
2475 && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2476 }
2477
2478 pub fn same_type_modulo_infer<T: relate::Relate<TyCtxt<'tcx>>>(&self, a: T, b: T) -> bool {
2486 let (a, b) = self.deeply_resolve_ignoring_regions((a, b));
2487 SameTypeModuloInfer(self).relate(a, b).is_ok()
2488 }
2489}
2490
2491struct SameTypeModuloInfer<'a, 'tcx>(&'a InferCtxt<'tcx>);
2492
2493impl<'tcx> TypeRelation<TyCtxt<'tcx>> for SameTypeModuloInfer<'_, 'tcx> {
2494 fn cx(&self) -> TyCtxt<'tcx> {
2495 self.0.tcx
2496 }
2497
2498 fn relate_ty_args(
2499 &mut self,
2500 a_ty: Ty<'tcx>,
2501 _: Ty<'tcx>,
2502 _: DefId,
2503 a_args: ty::GenericArgs<'tcx>,
2504 b_args: ty::GenericArgs<'tcx>,
2505 _: impl FnOnce(ty::GenericArgs<'tcx>) -> Ty<'tcx>,
2506 ) -> RelateResult<'tcx, Ty<'tcx>> {
2507 relate::relate_args_invariantly(self, a_args, b_args)?;
2508 Ok(a_ty)
2509 }
2510
2511 fn relate_with_variance<T: relate::Relate<TyCtxt<'tcx>>>(
2512 &mut self,
2513 _variance: ty::Variance,
2514 _info: ty::VarianceDiagInfo<TyCtxt<'tcx>>,
2515 a: T,
2516 b: T,
2517 ) -> relate::RelateResult<'tcx, T> {
2518 self.relate(a, b)
2519 }
2520
2521 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
2522 match (a.kind(), b.kind()) {
2523 (ty::Int(_) | ty::Uint(_), ty::Infer(ty::InferTy::IntVar(_)))
2524 | (
2525 ty::Infer(ty::InferTy::IntVar(_)),
2526 ty::Int(_) | ty::Uint(_) | ty::Infer(ty::InferTy::IntVar(_)),
2527 )
2528 | (ty::Float(_), ty::Infer(ty::InferTy::FloatVar(_)))
2529 | (
2530 ty::Infer(ty::InferTy::FloatVar(_)),
2531 ty::Float(_) | ty::Infer(ty::InferTy::FloatVar(_)),
2532 )
2533 | (ty::Infer(ty::InferTy::TyVar(_)), _)
2534 | (_, ty::Infer(ty::InferTy::TyVar(_)))
2535 | (ty::Alias(IsRigid::No, _), _)
2536 | (_, ty::Alias(IsRigid::No, _)) => Ok(a),
2537 (ty::Infer(_), _) | (_, ty::Infer(_)) => Err(TypeError::Mismatch),
2538 _ => relate::structurally_relate_tys(self, a, b),
2539 }
2540 }
2541
2542 fn regions(
2543 &mut self,
2544 a: ty::Region<'tcx>,
2545 b: ty::Region<'tcx>,
2546 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
2547 if (a.is_var() && b.is_free())
2548 || (b.is_var() && a.is_free())
2549 || (a.is_var() && b.is_var())
2550 || a == b
2551 {
2552 Ok(a)
2553 } else {
2554 Err(TypeError::Mismatch)
2555 }
2556 }
2557
2558 fn binders<T>(
2559 &mut self,
2560 a: ty::Binder<'tcx, T>,
2561 b: ty::Binder<'tcx, T>,
2562 ) -> relate::RelateResult<'tcx, ty::Binder<'tcx, T>>
2563 where
2564 T: relate::Relate<TyCtxt<'tcx>>,
2565 {
2566 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
2567 }
2568
2569 fn consts(
2570 &mut self,
2571 a: ty::Const<'tcx>,
2572 _b: ty::Const<'tcx>,
2573 ) -> relate::RelateResult<'tcx, ty::Const<'tcx>> {
2574 Ok(a)
2577 }
2578}
2579
2580pub enum FailureCode {
2581 Error0317,
2582 Error0580,
2583 Error0308,
2584 Error0644,
2585}
2586
2587pub trait ObligationCauseExt<'tcx> {
fn as_failure_code(&self, terr: TypeError<'tcx>)
-> FailureCode;
fn as_failure_code_diag(&self, terr: TypeError<'tcx>, span: Span,
subdiags: Vec<TypeErrorAdditionalDiags>)
-> ObligationCauseFailureCode;
fn as_requirement_str(&self)
-> &'static str;
}
impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
match self.code() {
ObligationCauseCode::IfExpressionWithNoElse =>
FailureCode::Error0317,
ObligationCauseCode::MainFunctionType => FailureCode::Error0580,
ObligationCauseCode::CompareImplItem { .. } |
ObligationCauseCode::MatchExpressionArm(_) |
ObligationCauseCode::IfExpression { .. } |
ObligationCauseCode::LetElse |
ObligationCauseCode::LangFunctionType(_) |
ObligationCauseCode::IntrinsicType |
ObligationCauseCode::MethodReceiver => FailureCode::Error0308,
_ =>
match terr {
TypeError::CyclicTy(ty) if
ty.is_closure() || ty.is_coroutine() ||
ty.is_coroutine_closure() => {
FailureCode::Error0644
}
TypeError::IntrinsicCast | TypeError::ForceInlineCast =>
FailureCode::Error0308,
_ => FailureCode::Error0308,
},
}
}
fn as_failure_code_diag(&self, terr: TypeError<'tcx>, span: Span,
subdiags: Vec<TypeErrorAdditionalDiags>)
-> ObligationCauseFailureCode {
match self.code() {
ObligationCauseCode::CompareImplItem {
kind: ty::AssocKind::Fn { .. }, .. } => {
ObligationCauseFailureCode::MethodCompat { span, subdiags }
}
ObligationCauseCode::CompareImplItem {
kind: ty::AssocKind::Type { .. }, .. } => {
ObligationCauseFailureCode::TypeCompat { span, subdiags }
}
ObligationCauseCode::CompareImplItem {
kind: ty::AssocKind::Const { .. }, .. } => {
ObligationCauseFailureCode::ConstCompat { span, subdiags }
}
ObligationCauseCode::BlockTailExpression(..,
hir::MatchSource::TryDesugar(_)) => {
ObligationCauseFailureCode::TryCompat { span, subdiags }
}
ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
source, .. }) => {
match source {
hir::MatchSource::TryDesugar(_) => {
ObligationCauseFailureCode::TryCompat { span, subdiags }
}
_ =>
ObligationCauseFailureCode::MatchCompat { span, subdiags },
}
}
ObligationCauseCode::IfExpression { .. } => {
ObligationCauseFailureCode::IfElseDifferent { span, subdiags }
}
ObligationCauseCode::IfExpressionWithNoElse => {
ObligationCauseFailureCode::NoElse { span }
}
ObligationCauseCode::LetElse => {
ObligationCauseFailureCode::NoDiverge { span, subdiags }
}
ObligationCauseCode::MainFunctionType => {
ObligationCauseFailureCode::FnMainCorrectType { span }
}
&ObligationCauseCode::LangFunctionType(lang_item_name) => {
ObligationCauseFailureCode::FnLangCorrectType {
span,
subdiags,
lang_item_name,
}
}
ObligationCauseCode::IntrinsicType => {
ObligationCauseFailureCode::IntrinsicCorrectType {
span,
subdiags,
}
}
ObligationCauseCode::MethodReceiver => {
ObligationCauseFailureCode::MethodCorrectType {
span,
subdiags,
}
}
_ =>
match terr {
TypeError::CyclicTy(ty) if
ty.is_closure() || ty.is_coroutine() ||
ty.is_coroutine_closure() => {
ObligationCauseFailureCode::ClosureSelfref { span }
}
TypeError::ForceInlineCast => {
ObligationCauseFailureCode::CantCoerceForceInline {
span,
subdiags,
}
}
TypeError::IntrinsicCast => {
ObligationCauseFailureCode::CantCoerceIntrinsic {
span,
subdiags,
}
}
_ => ObligationCauseFailureCode::Generic { span, subdiags },
},
}
}
fn as_requirement_str(&self) -> &'static str {
match self.code() {
ObligationCauseCode::CompareImplItem {
kind: ty::AssocKind::Fn { .. }, .. } => {
"method type is compatible with trait"
}
ObligationCauseCode::CompareImplItem {
kind: ty::AssocKind::Type { .. }, .. } => {
"associated type is compatible with trait"
}
ObligationCauseCode::CompareImplItem {
kind: ty::AssocKind::Const { .. }, .. } => {
"const is compatible with trait"
}
ObligationCauseCode::MainFunctionType =>
"`main` function has the correct type",
ObligationCauseCode::LangFunctionType(_) =>
"lang item function has the correct type",
ObligationCauseCode::IntrinsicType =>
"intrinsic has the correct type",
ObligationCauseCode::MethodReceiver =>
"method receiver has the correct type",
_ => "types are compatible",
}
}
}#[extension(pub trait ObligationCauseExt<'tcx>)]
2588impl<'tcx> ObligationCause<'tcx> {
2589 fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
2590 match self.code() {
2591 ObligationCauseCode::IfExpressionWithNoElse => FailureCode::Error0317,
2592 ObligationCauseCode::MainFunctionType => FailureCode::Error0580,
2593 ObligationCauseCode::CompareImplItem { .. }
2594 | ObligationCauseCode::MatchExpressionArm(_)
2595 | ObligationCauseCode::IfExpression { .. }
2596 | ObligationCauseCode::LetElse
2597 | ObligationCauseCode::LangFunctionType(_)
2598 | ObligationCauseCode::IntrinsicType
2599 | ObligationCauseCode::MethodReceiver => FailureCode::Error0308,
2600
2601 _ => match terr {
2605 TypeError::CyclicTy(ty)
2606 if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() =>
2607 {
2608 FailureCode::Error0644
2609 }
2610 TypeError::IntrinsicCast | TypeError::ForceInlineCast => FailureCode::Error0308,
2611 _ => FailureCode::Error0308,
2612 },
2613 }
2614 }
2615
2616 fn as_failure_code_diag(
2617 &self,
2618 terr: TypeError<'tcx>,
2619 span: Span,
2620 subdiags: Vec<TypeErrorAdditionalDiags>,
2621 ) -> ObligationCauseFailureCode {
2622 match self.code() {
2623 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2624 ObligationCauseFailureCode::MethodCompat { span, subdiags }
2625 }
2626 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2627 ObligationCauseFailureCode::TypeCompat { span, subdiags }
2628 }
2629 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2630 ObligationCauseFailureCode::ConstCompat { span, subdiags }
2631 }
2632 ObligationCauseCode::BlockTailExpression(.., hir::MatchSource::TryDesugar(_)) => {
2633 ObligationCauseFailureCode::TryCompat { span, subdiags }
2634 }
2635 ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause { source, .. }) => {
2636 match source {
2637 hir::MatchSource::TryDesugar(_) => {
2638 ObligationCauseFailureCode::TryCompat { span, subdiags }
2639 }
2640 _ => ObligationCauseFailureCode::MatchCompat { span, subdiags },
2641 }
2642 }
2643 ObligationCauseCode::IfExpression { .. } => {
2644 ObligationCauseFailureCode::IfElseDifferent { span, subdiags }
2645 }
2646 ObligationCauseCode::IfExpressionWithNoElse => {
2647 ObligationCauseFailureCode::NoElse { span }
2648 }
2649 ObligationCauseCode::LetElse => {
2650 ObligationCauseFailureCode::NoDiverge { span, subdiags }
2651 }
2652 ObligationCauseCode::MainFunctionType => {
2653 ObligationCauseFailureCode::FnMainCorrectType { span }
2654 }
2655 &ObligationCauseCode::LangFunctionType(lang_item_name) => {
2656 ObligationCauseFailureCode::FnLangCorrectType { span, subdiags, lang_item_name }
2657 }
2658 ObligationCauseCode::IntrinsicType => {
2659 ObligationCauseFailureCode::IntrinsicCorrectType { span, subdiags }
2660 }
2661 ObligationCauseCode::MethodReceiver => {
2662 ObligationCauseFailureCode::MethodCorrectType { span, subdiags }
2663 }
2664
2665 _ => match terr {
2669 TypeError::CyclicTy(ty)
2670 if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() =>
2671 {
2672 ObligationCauseFailureCode::ClosureSelfref { span }
2673 }
2674 TypeError::ForceInlineCast => {
2675 ObligationCauseFailureCode::CantCoerceForceInline { span, subdiags }
2676 }
2677 TypeError::IntrinsicCast => {
2678 ObligationCauseFailureCode::CantCoerceIntrinsic { span, subdiags }
2679 }
2680 _ => ObligationCauseFailureCode::Generic { span, subdiags },
2681 },
2682 }
2683 }
2684
2685 fn as_requirement_str(&self) -> &'static str {
2686 match self.code() {
2687 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2688 "method type is compatible with trait"
2689 }
2690 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2691 "associated type is compatible with trait"
2692 }
2693 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2694 "const is compatible with trait"
2695 }
2696 ObligationCauseCode::MainFunctionType => "`main` function has the correct type",
2697 ObligationCauseCode::LangFunctionType(_) => "lang item function has the correct type",
2698 ObligationCauseCode::IntrinsicType => "intrinsic has the correct type",
2699 ObligationCauseCode::MethodReceiver => "method receiver has the correct type",
2700 _ => "types are compatible",
2701 }
2702 }
2703}
2704
2705pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
2707
2708impl IntoDiagArg for ObligationCauseAsDiagArg<'_> {
2709 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
2710 let kind = match self.0.code() {
2711 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2712 "method_compat"
2713 }
2714 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2715 "type_compat"
2716 }
2717 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2718 "const_compat"
2719 }
2720 ObligationCauseCode::MainFunctionType => "fn_main_correct_type",
2721 ObligationCauseCode::LangFunctionType(_) => "fn_lang_correct_type",
2722 ObligationCauseCode::IntrinsicType => "intrinsic_correct_type",
2723 ObligationCauseCode::MethodReceiver => "method_correct_type",
2724 _ => "other",
2725 }
2726 .into();
2727 rustc_errors::DiagArgValue::Str(kind)
2728 }
2729}
2730
2731#[derive(#[automatically_derived]#[doc(hidden)]unsafe impl ::core::clone::TrivialClone
for TyCategory {
}
#[automatically_derived]impl ::core::clone::Clone for TyCategory {
#[inline]
#[rustc_trivial_field_reads]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<hir::CoroutineKind>;
*self
}
}Clone, #[automatically_derived]impl ::core::marker::Copy for TyCategory { }Copy, #[automatically_derived]impl ::core::marker::StructuralPartialEq for
TyCategory {
}
#[automatically_derived]impl ::core::cmp::PartialEq for TyCategory {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::Coroutine(__self_0), Self::Coroutine(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for TyCategory {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<hir::CoroutineKind>;
}
}Eq, #[automatically_derived]impl ::core::hash::Hash for TyCategory {
#[inline]
fn hash<__H: ::core::hash::Hasher>(&self, state: &mut __H) {
::core::hash::Hash::hash(&::core::intrinsics::discriminant_value(self),
state);
match self {
Self::Coroutine(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash)]
2734pub enum TyCategory {
2735 Closure,
2736 Opaque,
2737 OpaqueFuture,
2738 Coroutine(hir::CoroutineKind),
2739 Foreign,
2740}
2741
2742impl fmt::Display for TyCategory {
2743 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2744 match self {
2745 Self::Closure => "closure".fmt(f),
2746 Self::Opaque => "opaque type".fmt(f),
2747 Self::OpaqueFuture => "future".fmt(f),
2748 Self::Coroutine(gk) => gk.fmt(f),
2749 Self::Foreign => "foreign type".fmt(f),
2750 }
2751 }
2752}
2753
2754impl TyCategory {
2755 pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2756 match *ty.kind() {
2757 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2758 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
2759 let kind =
2760 if tcx.ty_is_opaque_future(ty) { Self::OpaqueFuture } else { Self::Opaque };
2761 Some((kind, def_id))
2762 }
2763 ty::Coroutine(def_id, ..) => {
2764 Some((Self::Coroutine(tcx.coroutine_kind(def_id).unwrap()), def_id))
2765 }
2766 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
2767 _ => None,
2768 }
2769 }
2770}