1use std::borrow::Cow;
49use std::ops::ControlFlow;
50use std::path::PathBuf;
51use std::{cmp, fmt, iter};
52
53use rustc_abi::ExternAbi;
54use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
55use rustc_errors::{Applicability, Diag, DiagStyledString, IntoDiagArg, StringPart, pluralize};
56use rustc_hir::attrs::diagnostic::{CustomDiagnostic, Directive, FormatArgs};
57use rustc_hir::def_id::{CRATE_DEF_ID, DefId};
58use rustc_hir::intravisit::Visitor;
59use rustc_hir::{self as hir, find_attr};
60use rustc_infer::infer::DefineOpaqueTypes;
61use rustc_macros::extension;
62use rustc_middle::bug;
63use rustc_middle::traits::PatternOriginExpr;
64use rustc_middle::ty::error::{ExpectedFound, TypeError, TypeErrorToStringExt};
65use rustc_middle::ty::print::{PrintTraitRefExt as _, WrapBinderMode, with_forced_trimmed_paths};
66use rustc_middle::ty::{
67 self, List, ParamEnv, Region, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable, TypeVisitable,
68 TypeVisitableExt, Unnormalized,
69};
70use rustc_span::{BytePos, DUMMY_SP, DesugaringKind, Pos, Span, sym};
71use thin_vec::ThinVec;
72use tracing::{debug, instrument};
73
74use crate::diagnostics::{ObligationCauseFailureCode, TypeErrorAdditionalDiags};
75use crate::error_reporting::TypeErrCtxt;
76use crate::error_reporting::traits::ambiguity::{
77 CandidateSource, compute_applicable_impls_for_diagnostics,
78};
79use crate::infer;
80use crate::infer::relate::{self, RelateResult, TypeRelation};
81use crate::infer::{InferCtxt, InferCtxtExt as _, TypeTrace, ValuePairs};
82use crate::solve::deeply_normalize_for_diagnostics;
83use crate::traits::{
84 MatchExpressionArmCause, Obligation, ObligationCause, ObligationCauseCode, ObligationCtxt,
85 specialization_graph,
86};
87
88mod note_and_explain;
89mod suggest;
90
91pub mod need_type_info;
92pub mod nice_region_error;
93pub mod region;
94
95fn escape_literal(s: &str) -> String {
98 let mut escaped = String::with_capacity(s.len());
99 let mut chrs = s.chars().peekable();
100 while let Some(first) = chrs.next() {
101 match (first, chrs.peek()) {
102 ('\\', Some(&delim @ '"') | Some(&delim @ '\'')) => {
103 escaped.push('\\');
104 escaped.push(delim);
105 chrs.next();
106 }
107 ('"' | '\'', _) => {
108 escaped.push('\\');
109 escaped.push(first)
110 }
111 (c, _) => escaped.push(c),
112 };
113 }
114 escaped
115}
116
117impl<'a, 'tcx> TypeErrCtxt<'a, 'tcx> {
118 fn normalize_fn_sig(
119 &self,
120 fn_sig: Unnormalized<'tcx, ty::PolyFnSig<'tcx>>,
121 ) -> ty::PolyFnSig<'tcx> {
122 let Some(param_env) = self.param_env else {
123 return fn_sig.skip_normalization();
124 };
125
126 if fn_sig.skip_normalization().has_escaping_bound_vars() {
127 return fn_sig.skip_normalization();
128 }
129
130 self.probe(|_| {
131 let ocx = ObligationCtxt::new(self);
132 let normalized_fn_sig = ocx.normalize(&ObligationCause::dummy(), param_env, fn_sig);
133 if ocx.evaluate_obligations_error_on_ambiguity().is_empty() {
134 let normalized_fn_sig = self.resolve_vars_if_possible(normalized_fn_sig);
135 if !normalized_fn_sig.has_infer() {
136 return normalized_fn_sig;
137 }
138 }
139 fn_sig.skip_normalization()
140 })
141 }
142
143 pub fn type_error_struct_with_diag<M>(
154 &self,
155 sp: Span,
156 mk_diag: M,
157 actual_ty: Ty<'tcx>,
158 ) -> Diag<'a>
159 where
160 M: FnOnce(String) -> Diag<'a>,
161 {
162 let actual_ty = self.resolve_vars_if_possible(actual_ty);
163 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:163",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(163u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("type_error_struct_with_diag({0:?}, {1:?})",
sp, actual_ty) as &dyn Value))])
});
} else { ; }
};debug!("type_error_struct_with_diag({:?}, {:?})", sp, actual_ty);
164
165 let mut err = mk_diag(self.ty_to_string(actual_ty));
166
167 if actual_ty.references_error() {
169 err.downgrade_to_delayed_bug();
170 }
171
172 err
173 }
174
175 pub fn report_mismatched_types(
176 &self,
177 cause: &ObligationCause<'tcx>,
178 param_env: ty::ParamEnv<'tcx>,
179 expected: Ty<'tcx>,
180 actual: Ty<'tcx>,
181 err: TypeError<'tcx>,
182 ) -> Diag<'a> {
183 let mut diag = self.report_and_explain_type_error(
184 TypeTrace::types(cause, expected, actual),
185 param_env,
186 err,
187 );
188
189 self.suggest_param_env_shadowing(&mut diag, expected, actual, param_env);
190
191 diag
192 }
193
194 pub fn report_mismatched_consts(
195 &self,
196 cause: &ObligationCause<'tcx>,
197 param_env: ty::ParamEnv<'tcx>,
198 expected: ty::Const<'tcx>,
199 actual: ty::Const<'tcx>,
200 err: TypeError<'tcx>,
201 ) -> Diag<'a> {
202 self.report_and_explain_type_error(
203 TypeTrace::consts(cause, expected, actual),
204 param_env,
205 err,
206 )
207 }
208
209 fn check_and_note_conflicting_crates(&self, err: &mut Diag<'_>, terr: TypeError<'tcx>) -> bool {
211 match terr {
212 TypeError::Sorts(ref exp_found) => {
213 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
216 (exp_found.expected.kind(), exp_found.found.kind())
217 {
218 return self.check_same_definition_different_crate(
219 err,
220 exp_adt.did(),
221 [found_adt.did()].into_iter(),
222 |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)],
223 "type",
224 );
225 }
226 }
227 TypeError::Traits(ref exp_found) => {
228 return self.check_same_definition_different_crate(
229 err,
230 exp_found.expected,
231 [exp_found.found].into_iter(),
232 |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)],
233 "trait",
234 );
235 }
236 _ => (), }
238 false
239 }
240
241 fn suggest_param_env_shadowing(
242 &self,
243 diag: &mut Diag<'_>,
244 expected: Ty<'tcx>,
245 found: Ty<'tcx>,
246 param_env: ty::ParamEnv<'tcx>,
247 ) {
248 let (alias, &def_id, concrete) = match (expected.kind(), found.kind()) {
249 (ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { def_id }, .. }), _) => {
250 (proj, def_id, found)
251 }
252 (_, ty::Alias(_, proj @ ty::AliasTy { kind: ty::Projection { def_id }, .. })) => {
253 (proj, def_id, expected)
254 }
255 _ => return,
256 };
257
258 let tcx = self.tcx;
259
260 let trait_ref = alias.trait_ref(tcx);
261 let obligation =
262 Obligation::new(tcx, ObligationCause::dummy(), param_env, ty::Binder::dummy(trait_ref));
263
264 let applicable_impls =
265 compute_applicable_impls_for_diagnostics(self.infcx, &obligation, false);
266
267 for candidate in applicable_impls {
268 let impl_def_id = match candidate {
269 CandidateSource::DefId(did) => did,
270 CandidateSource::ParamEnv(_) => continue,
271 };
272
273 let is_shadowed = self.infcx.probe(|_| {
274 let impl_substs = self.infcx.fresh_args_for_item(DUMMY_SP, impl_def_id);
275 let impl_trait_ref =
276 tcx.impl_trait_ref(impl_def_id).instantiate(tcx, impl_substs).skip_norm_wip();
277
278 let expected_trait_ref = alias.trait_ref(tcx);
279
280 if let Err(_) = self.infcx.at(&ObligationCause::dummy(), param_env).eq(
281 DefineOpaqueTypes::No,
282 expected_trait_ref,
283 impl_trait_ref,
284 ) {
285 return false;
286 }
287
288 let leaf_def = match specialization_graph::assoc_def(tcx, impl_def_id, def_id) {
289 Ok(leaf) => leaf,
290 Err(_) => return false,
291 };
292
293 let trait_def_id = alias.trait_def_id(tcx);
294 let rebased_args = alias.args.rebase_onto(tcx, trait_def_id, impl_substs);
295
296 if !leaf_def.item.defaultness(tcx).has_value() {
299 return false;
300 }
301
302 let impl_item_def_id = leaf_def.item.def_id;
303 if !tcx.check_args_compatible(impl_item_def_id, rebased_args) {
304 return false;
305 }
306 let impl_assoc_ty =
307 tcx.type_of(impl_item_def_id).instantiate(tcx, rebased_args).skip_norm_wip();
308
309 self.infcx.can_eq(param_env, impl_assoc_ty, concrete)
310 });
311
312 if is_shadowed {
313 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!(
314 "the associated type `{}` is defined as `{}` in the implementation, \
315 but the where-bound `{}` shadows this definition\n\
316 see issue #152409 <https://github.com/rust-lang/rust/issues/152409> for more information",
317 self.ty_to_string(alias.to_ty(tcx, ty::IsRigid::No)),
318 self.ty_to_string(concrete),
319 self.ty_to_string(alias.self_ty())
320 ));
321 return;
322 }
323 }
324 }
325
326 fn note_error_origin(
327 &self,
328 err: &mut Diag<'_>,
329 cause: &ObligationCause<'tcx>,
330 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
331 terr: TypeError<'tcx>,
332 param_env: Option<ParamEnv<'tcx>>,
333 ) {
334 match *cause.code() {
335 ObligationCauseCode::Pattern {
336 origin_expr: Some(origin_expr),
337 span: Some(span),
338 root_ty,
339 } => {
340 let expected_ty = self.resolve_vars_if_possible(root_ty);
341 if !#[allow(non_exhaustive_omitted_patterns)] match expected_ty.kind() {
ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)) => true,
_ => false,
}matches!(
342 expected_ty.kind(),
343 ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_))
344 ) {
345 if span.desugaring_kind() == Some(DesugaringKind::ForLoop)
347 && let ty::Adt(def, args) = expected_ty.kind()
348 && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option)
349 {
350 err.span_label(
351 span,
352 ::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)),
353 );
354 } else if !span.overlaps(cause.span) {
355 let expected_ty = self.tcx.short_string(expected_ty, err.long_ty_path());
356 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}`"));
357 }
358 }
359 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
360 && let Ok(mut peeled_snippet) =
361 self.tcx.sess.source_map().span_to_snippet(origin_expr.peeled_span)
362 {
363 if origin_expr.peeled_prefix_suggestion_parentheses {
368 peeled_snippet = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("({0})", peeled_snippet))
})format!("({peeled_snippet})");
369 }
370
371 if expected_ty.boxed_ty() == Some(found) {
374 err.span_suggestion_verbose(
375 span,
376 "consider dereferencing the boxed value",
377 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("*{0}", peeled_snippet))
})format!("*{peeled_snippet}"),
378 Applicability::MachineApplicable,
379 );
380 } else if let Some(param_env) = param_env
381 && let Some(prefix) = self.should_deref_suggestion_on_mismatch(
382 param_env,
383 found,
384 expected_ty,
385 origin_expr,
386 )
387 {
388 err.span_suggestion_verbose(
389 span,
390 "consider dereferencing to access the inner value using the `Deref` trait",
391 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}{1}", prefix, peeled_snippet))
})format!("{prefix}{peeled_snippet}"),
392 Applicability::MaybeIncorrect,
393 );
394 }
395 }
396 }
397 ObligationCauseCode::Pattern { origin_expr: None, span: Some(span), .. } => {
398 err.span_label(span, "expected due to this");
399 }
400 ObligationCauseCode::BlockTailExpression(
401 _,
402 hir::MatchSource::TryDesugar(scrut_hir_id),
403 ) => {
404 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
405 let scrut_expr = self.tcx.hir_expect_expr(scrut_hir_id);
406 let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
407 let arg_expr = args.first().expect("try desugaring call w/out arg");
408 self.typeck_results
409 .as_ref()
410 .and_then(|typeck_results| typeck_results.expr_ty_opt(arg_expr))
411 } else {
412 ::rustc_middle::util::bug::bug_fmt(format_args!("try desugaring w/out call expr as scrutinee"));bug!("try desugaring w/out call expr as scrutinee");
413 };
414
415 match scrut_ty {
416 Some(ty) if expected == ty => {
417 let source_map = self.tcx.sess.source_map();
418 err.span_suggestion(
419 source_map.end_point(cause.span),
420 "try removing this `?`",
421 "",
422 Applicability::MachineApplicable,
423 );
424 }
425 _ => {}
426 }
427 }
428 }
429 ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
430 arm_block_id,
431 arm_span,
432 arm_ty,
433 prior_arm_block_id,
434 prior_arm_span,
435 prior_arm_ty,
436 source,
437 ref prior_non_diverging_arms,
438 scrut_span,
439 expr_span,
440 ..
441 }) => match source {
442 hir::MatchSource::TryDesugar(scrut_hir_id) => {
443 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
444 let scrut_expr = self.tcx.hir_expect_expr(scrut_hir_id);
445 let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
446 let arg_expr = args.first().expect("try desugaring call w/out arg");
447 self.typeck_results
448 .as_ref()
449 .and_then(|typeck_results| typeck_results.expr_ty_opt(arg_expr))
450 } else {
451 ::rustc_middle::util::bug::bug_fmt(format_args!("try desugaring w/out call expr as scrutinee"));bug!("try desugaring w/out call expr as scrutinee");
452 };
453
454 match scrut_ty {
455 Some(ty) if expected == ty => {
456 let source_map = self.tcx.sess.source_map();
457 err.span_suggestion(
458 source_map.end_point(cause.span),
459 "try removing this `?`",
460 "",
461 Applicability::MachineApplicable,
462 );
463 }
464 _ => {}
465 }
466 }
467 }
468 _ => {
469 let t = self.resolve_vars_if_possible(match exp_found {
471 Some(ty::error::ExpectedFound { expected, .. }) => expected,
472 _ => prior_arm_ty,
473 });
474 let source_map = self.tcx.sess.source_map();
475 let mut any_multiline_arm = source_map.is_multiline(arm_span);
476 if prior_non_diverging_arms.len() <= 4 {
477 for sp in prior_non_diverging_arms {
478 any_multiline_arm |= source_map.is_multiline(*sp);
479 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}`"));
480 }
481 } else if let Some(sp) = prior_non_diverging_arms.last() {
482 any_multiline_arm |= source_map.is_multiline(*sp);
483 err.span_label(
484 *sp,
485 ::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}`"),
486 );
487 }
488 let outer = if any_multiline_arm || !source_map.is_multiline(expr_span) {
489 expr_span.shrink_to_lo().to(scrut_span)
492 } else {
493 expr_span
494 };
495 let msg = "`match` arms have incompatible types";
496 err.span_label(outer, msg);
497 if let Some(subdiag) = self.suggest_remove_semi_or_return_binding(
498 prior_arm_block_id,
499 prior_arm_ty,
500 prior_arm_span,
501 arm_block_id,
502 arm_ty,
503 arm_span,
504 ) {
505 err.subdiagnostic(subdiag);
506 }
507 }
508 },
509 ObligationCauseCode::IfExpression { expr_id, .. } => {
510 let hir::Node::Expr(&hir::Expr {
511 kind: hir::ExprKind::If(cond_expr, then_expr, Some(else_expr)),
512 span: expr_span,
513 ..
514 }) = self.tcx.hir_node(expr_id)
515 else {
516 return;
517 };
518 let then_span = self.find_block_span_from_hir_id(then_expr.hir_id);
519 let then_ty = self
520 .typeck_results
521 .as_ref()
522 .expect("if expression only expected inside FnCtxt")
523 .expr_ty(then_expr);
524 let else_span = self.find_block_span_from_hir_id(else_expr.hir_id);
525 let else_ty = self
526 .typeck_results
527 .as_ref()
528 .expect("if expression only expected inside FnCtxt")
529 .expr_ty(else_expr);
530 if let hir::ExprKind::If(_cond, _then, None) = else_expr.kind
531 && else_ty.is_unit()
532 {
533 err.note("`if` expressions without `else` evaluate to `()`");
535 err.note("consider adding an `else` block that evaluates to the expected type");
536 }
537 err.span_label(then_span, "expected because of this");
538
539 let outer_span = if self.tcx.sess.source_map().is_multiline(expr_span) {
540 if then_span.hi() == expr_span.hi() || else_span.hi() == expr_span.hi() {
541 Some(expr_span.shrink_to_lo().to(cond_expr.peel_drop_temps().span))
544 } else {
545 Some(expr_span)
546 }
547 } else {
548 None
549 };
550 if let Some(sp) = outer_span {
551 err.span_label(sp, "`if` and `else` have incompatible types");
552 }
553
554 let then_id = if let hir::ExprKind::Block(then_blk, _) = then_expr.kind {
555 then_blk.hir_id
556 } else {
557 then_expr.hir_id
558 };
559 let else_id = if let hir::ExprKind::Block(else_blk, _) = else_expr.kind {
560 else_blk.hir_id
561 } else {
562 else_expr.hir_id
563 };
564 if let Some(subdiag) = self.suggest_remove_semi_or_return_binding(
565 Some(then_id),
566 then_ty,
567 then_span,
568 Some(else_id),
569 else_ty,
570 else_span,
571 ) {
572 err.subdiagnostic(subdiag);
573 }
574 }
575 ObligationCauseCode::LetElse => {
576 err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
577 err.help("...or use `match` instead of `let...else`");
578 }
579 _ => {
580 if let ObligationCauseCode::WhereClause(_, span)
581 | ObligationCauseCode::WhereClauseInExpr(_, span, ..) =
582 cause.code().peel_derives()
583 && !span.is_dummy()
584 && let TypeError::RegionsPlaceholderMismatch = terr
585 {
586 err.span_note(*span, "the lifetime requirement is introduced here");
587 }
588 }
589 }
590 }
591
592 fn should_deref_suggestion_on_mismatch(
595 &self,
596 param_env: ParamEnv<'tcx>,
597 deref_to: Ty<'tcx>,
598 deref_from: Ty<'tcx>,
599 origin_expr: PatternOriginExpr,
600 ) -> Option<String> {
601 let Some((num_derefs, (after_deref_ty, _))) = (self.autoderef_steps)(deref_from)
609 .into_iter()
610 .enumerate()
611 .find(|(_, (ty, _))| self.infcx.can_eq(param_env, *ty, deref_to))
612 else {
613 return None;
614 };
615
616 if num_derefs <= origin_expr.peeled_count {
617 return None;
618 }
619
620 let deref_part = "*".repeat(num_derefs - origin_expr.peeled_count);
621
622 if deref_from.is_ref() && !after_deref_ty.is_ref() {
625 Some(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&{0}", deref_part))
})format!("&{deref_part}"))
626 } else {
627 Some(deref_part)
628 }
629 }
630
631 fn highlight_outer(
645 &self,
646 value: &mut DiagStyledString,
647 other_value: &mut DiagStyledString,
648 name: String,
649 args: &[ty::GenericArg<'tcx>],
650 pos: usize,
651 other_ty: Ty<'tcx>,
652 ) {
653 value.push_highlighted(name);
656
657 if args.is_empty() {
658 return;
659 }
660 value.push_highlighted("<");
661
662 for (i, arg) in args.iter().enumerate() {
663 if i > 0 {
664 value.push_normal(", ");
665 }
666
667 match arg.kind() {
668 ty::GenericArgKind::Lifetime(lt) => {
669 let s = lt.to_string();
670 value.push_normal(if s.is_empty() { "'_" } else { &s });
671 }
672 ty::GenericArgKind::Const(ct) => {
673 value.push_normal(ct.to_string());
674 }
675 ty::GenericArgKind::Type(type_arg) => {
678 if i == pos {
679 let values = self.cmp(type_arg, other_ty);
680 value.0.extend((values.0).0);
681 other_value.0.extend((values.1).0);
682 } else {
683 value.push_highlighted(type_arg.to_string());
684 }
685 }
686 }
687 }
688
689 value.push_highlighted(">");
690 }
691
692 fn cmp_type_arg(
713 &self,
714 t1_out: &mut DiagStyledString,
715 t2_out: &mut DiagStyledString,
716 path: String,
717 args: &'tcx [ty::GenericArg<'tcx>],
718 other_path: String,
719 other_ty: Ty<'tcx>,
720 ) -> bool {
721 for (i, arg) in args.iter().enumerate() {
722 if let Some(ta) = arg.as_type() {
723 if ta == other_ty {
724 self.highlight_outer(t1_out, t2_out, path, args, i, other_ty);
725 return true;
726 }
727 if let ty::Adt(def, _) = ta.kind() {
728 let path_ = self.tcx.def_path_str(def.did());
729 if path_ == other_path {
730 self.highlight_outer(t1_out, t2_out, path, args, i, other_ty);
731 return true;
732 }
733 }
734 }
735 }
736 false
737 }
738
739 fn push_comma(
741 &self,
742 value: &mut DiagStyledString,
743 other_value: &mut DiagStyledString,
744 pos: usize,
745 ) {
746 if pos > 0 {
747 value.push_normal(", ");
748 other_value.push_normal(", ");
749 }
750 }
751
752 fn cmp_fn_sig(
754 &self,
755 sig1: ty::PolyFnSig<'tcx>,
756 fn_def1: Option<(DefId, Option<&'tcx [ty::GenericArg<'tcx>]>)>,
757 sig2: ty::PolyFnSig<'tcx>,
758 fn_def2: Option<(DefId, Option<&'tcx [ty::GenericArg<'tcx>]>)>,
759 ) -> (DiagStyledString, DiagStyledString) {
760 let sig1 = self.normalize_fn_sig(Unnormalized::new_wip(sig1));
761 let sig2 = self.normalize_fn_sig(Unnormalized::new_wip(sig2));
762
763 let get_lifetimes = |sig| {
764 use rustc_hir::def::Namespace;
765 let (sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
766 .name_all_regions(&sig, WrapBinderMode::ForAll)
767 .unwrap();
768 let lts: Vec<String> =
769 reg.into_items().map(|(_, kind)| kind.to_string()).into_sorted_stable_ord();
770 (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)
771 };
772
773 let (lt1, sig1) = get_lifetimes(sig1);
774 let (lt2, sig2) = get_lifetimes(sig2);
775
776 let mut values =
778 (DiagStyledString::normal("".to_string()), DiagStyledString::normal("".to_string()));
779
780 let fn_item_prefix_and_safety = |fn_def, sig: ty::FnSig<'_>| match fn_def {
783 None => ("", sig.safety().prefix_str()),
784 Some((did, _)) => {
785 if self.tcx.codegen_fn_attrs(did).safe_target_features {
786 ("#[target_features] ", "")
787 } else {
788 ("", sig.safety().prefix_str())
789 }
790 }
791 };
792 let (prefix1, safety1) = fn_item_prefix_and_safety(fn_def1, sig1);
793 let (prefix2, safety2) = fn_item_prefix_and_safety(fn_def2, sig2);
794 values.0.push(prefix1, prefix1 != prefix2);
795 values.1.push(prefix2, prefix1 != prefix2);
796
797 let lifetime_diff = lt1 != lt2;
800 values.0.push(lt1, lifetime_diff);
801 values.1.push(lt2, lifetime_diff);
802
803 values.0.push(safety1, safety1 != safety2);
806 values.1.push(safety2, safety1 != safety2);
807
808 if sig1.abi() != ExternAbi::Rust {
811 values.0.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("extern {0} ", sig1.abi()))
})format!("extern {} ", sig1.abi()), sig1.abi() != sig2.abi());
812 }
813 if sig2.abi() != ExternAbi::Rust {
814 values.1.push(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("extern {0} ", sig2.abi()))
})format!("extern {} ", sig2.abi()), sig1.abi() != sig2.abi());
815 }
816
817 values.0.push_normal("fn(");
820 values.1.push_normal("fn(");
821
822 let len1 = sig1.inputs().len();
825 let len2 = sig2.inputs().len();
826 if len1 == len2 {
827 for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
828 self.push_comma(&mut values.0, &mut values.1, i);
829 let (x1, x2) = self.cmp(*l, *r);
830 (values.0).0.extend(x1.0);
831 (values.1).0.extend(x2.0);
832 }
833 } else {
834 for (i, l) in sig1.inputs().iter().enumerate() {
835 values.0.push_highlighted(l.to_string());
836 if i != len1 - 1 {
837 values.0.push_highlighted(", ");
838 }
839 }
840 for (i, r) in sig2.inputs().iter().enumerate() {
841 values.1.push_highlighted(r.to_string());
842 if i != len2 - 1 {
843 values.1.push_highlighted(", ");
844 }
845 }
846 }
847
848 if sig1.c_variadic() {
849 if len1 > 0 {
850 values.0.push_normal(", ");
851 }
852 values.0.push("...", !sig2.c_variadic());
853 }
854 if sig2.c_variadic() {
855 if len2 > 0 {
856 values.1.push_normal(", ");
857 }
858 values.1.push("...", !sig1.c_variadic());
859 }
860
861 values.0.push_normal(")");
864 values.1.push_normal(")");
865
866 let output1 = sig1.output();
869 let output2 = sig2.output();
870 let (x1, x2) = self.cmp(output1, output2);
871 let output_diff = x1 != x2;
872 if !output1.is_unit() || output_diff {
873 values.0.push_normal(" -> ");
874 (values.0).0.extend(x1.0);
875 }
876 if !output2.is_unit() || output_diff {
877 values.1.push_normal(" -> ");
878 (values.1).0.extend(x2.0);
879 }
880
881 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));
882
883 match (fn_def1, fn_def2) {
884 (Some((fn_def1, Some(fn_args1))), Some((fn_def2, Some(fn_args2)))) => {
885 let path1 = fmt(fn_def1, fn_args1);
886 let path2 = fmt(fn_def2, fn_args2);
887 let same_path = path1 == path2;
888 values.0.push(path1, !same_path);
889 values.1.push(path2, !same_path);
890 }
891 (Some((fn_def1, Some(fn_args1))), None) => {
892 values.0.push_highlighted(fmt(fn_def1, fn_args1));
893 }
894 (None, Some((fn_def2, Some(fn_args2)))) => {
895 values.1.push_highlighted(fmt(fn_def2, fn_args2));
896 }
897 _ => {}
898 }
899
900 values
901 }
902
903 pub fn cmp_traits(
904 &self,
905 def_id1: DefId,
906 args1: &[ty::GenericArg<'tcx>],
907 def_id2: DefId,
908 args2: &[ty::GenericArg<'tcx>],
909 ) -> (DiagStyledString, DiagStyledString) {
910 let mut values = (DiagStyledString::new(), DiagStyledString::new());
911
912 if def_id1 != def_id2 {
913 values.0.push_highlighted(self.tcx.def_path_str(def_id1).as_str());
914 values.1.push_highlighted(self.tcx.def_path_str(def_id2).as_str());
915 } else {
916 values.0.push_normal(self.tcx.item_name(def_id1).as_str());
917 values.1.push_normal(self.tcx.item_name(def_id2).as_str());
918 }
919
920 if args1.len() != args2.len() {
921 let (pre, post) = if args1.len() > 0 { ("<", ">") } else { ("", "") };
922 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!(
923 "{pre}{}{post}",
924 args1.iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ")
925 ));
926 let (pre, post) = if args2.len() > 0 { ("<", ">") } else { ("", "") };
927 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!(
928 "{pre}{}{post}",
929 args2.iter().map(|a| a.to_string()).collect::<Vec<_>>().join(", ")
930 ));
931 return values;
932 }
933
934 if args1.len() > 0 {
935 values.0.push_normal("<");
936 values.1.push_normal("<");
937 }
938 for (i, (a, b)) in std::iter::zip(args1, args2).enumerate() {
939 let a_str = a.to_string();
940 let b_str = b.to_string();
941 if let (Some(a), Some(b)) = (a.as_type(), b.as_type()) {
942 let (a, b) = self.cmp(a, b);
943 values.0.0.extend(a.0);
944 values.1.0.extend(b.0);
945 } else if a_str != b_str {
946 values.0.push_highlighted(a_str);
947 values.1.push_highlighted(b_str);
948 } else {
949 values.0.push_normal(a_str);
950 values.1.push_normal(b_str);
951 }
952 if i + 1 < args1.len() {
953 values.0.push_normal(", ");
954 values.1.push_normal(", ");
955 }
956 }
957 if args1.len() > 0 {
958 values.0.push_normal(">");
959 values.1.push_normal(">");
960 }
961 values
962 }
963
964 pub fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagStyledString, DiagStyledString) {
967 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:967",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(967u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("cmp(t1={0}, t1.kind={1:?}, t2={2}, t2.kind={3:?})",
t1, t1.kind(), t2, t2.kind()) as &dyn Value))])
});
} else { ; }
};debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
968
969 let recurse = |t1, t2, values: &mut (DiagStyledString, DiagStyledString)| {
971 let (x1, x2) = self.cmp(t1, t2);
972 (values.0).0.extend(x1.0);
973 (values.1).0.extend(x2.0);
974 };
975
976 fn fmt_region<'tcx>(region: ty::Region<'tcx>) -> String {
977 let mut r = region.to_string();
978 if r == "'_" {
979 r.clear();
980 } else {
981 r.push(' ');
982 }
983 ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("&{0}", r)) })format!("&{r}")
984 }
985
986 fn push_ref<'tcx>(
987 region: ty::Region<'tcx>,
988 mutbl: hir::Mutability,
989 s: &mut DiagStyledString,
990 ) {
991 s.push_highlighted(fmt_region(region));
992 s.push_highlighted(mutbl.prefix_str());
993 }
994
995 fn maybe_highlight<T: Eq + ToString>(
996 t1: T,
997 t2: T,
998 (buf1, buf2): &mut (DiagStyledString, DiagStyledString),
999 tcx: TyCtxt<'_>,
1000 ) {
1001 let highlight = t1 != t2;
1002 let (t1, t2) = if highlight || tcx.sess.opts.verbose {
1003 (t1.to_string(), t2.to_string())
1004 } else {
1005 ("_".into(), "_".into())
1007 };
1008 buf1.push(t1, highlight);
1009 buf2.push(t2, highlight);
1010 }
1011
1012 fn cmp_ty_refs<'tcx>(
1013 r1: ty::Region<'tcx>,
1014 mut1: hir::Mutability,
1015 r2: ty::Region<'tcx>,
1016 mut2: hir::Mutability,
1017 ss: &mut (DiagStyledString, DiagStyledString),
1018 ) {
1019 let (r1, r2) = (fmt_region(r1), fmt_region(r2));
1020 if r1 != r2 {
1021 ss.0.push_highlighted(r1);
1022 ss.1.push_highlighted(r2);
1023 } else {
1024 ss.0.push_normal(r1);
1025 ss.1.push_normal(r2);
1026 }
1027
1028 if mut1 != mut2 {
1029 ss.0.push_highlighted(mut1.prefix_str());
1030 ss.1.push_highlighted(mut2.prefix_str());
1031 } else {
1032 ss.0.push_normal(mut1.prefix_str());
1033 ss.1.push_normal(mut2.prefix_str());
1034 }
1035 }
1036
1037 match (t1.kind(), t2.kind()) {
1039 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1040 let did1 = def1.did();
1041 let did2 = def2.did();
1042
1043 let generics1 = self.tcx.generics_of(did1);
1044 let generics2 = self.tcx.generics_of(did2);
1045
1046 let non_default_after_default = generics1
1047 .check_concrete_type_after_default(self.tcx, sub1)
1048 || generics2.check_concrete_type_after_default(self.tcx, sub2);
1049 let sub_no_defaults_1 = if non_default_after_default {
1050 generics1.own_args(sub1)
1051 } else {
1052 generics1.own_args_no_defaults(self.tcx, sub1)
1053 };
1054 let sub_no_defaults_2 = if non_default_after_default {
1055 generics2.own_args(sub2)
1056 } else {
1057 generics2.own_args_no_defaults(self.tcx, sub2)
1058 };
1059 let mut values = (DiagStyledString::new(), DiagStyledString::new());
1060 let path1 = self.tcx.def_path_str(did1);
1061 let path2 = self.tcx.def_path_str(did2);
1062 if did1 == did2 {
1063 values.0.push_normal(path1);
1072 values.1.push_normal(path2);
1073
1074 let len1 = sub_no_defaults_1.len();
1077 let len2 = sub_no_defaults_2.len();
1078 let common_len = cmp::min(len1, len2);
1079 let remainder1 = &sub1[common_len..];
1080 let remainder2 = &sub2[common_len..];
1081 let common_default_params =
1082 iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1083 .filter(|(a, b)| a == b)
1084 .count();
1085 let len = sub1.len() - common_default_params;
1086
1087 if len > 0 {
1089 values.0.push_normal("<");
1090 values.1.push_normal("<");
1091 }
1092
1093 fn lifetime_display(lifetime: Region<'_>) -> String {
1094 let s = lifetime.to_string();
1095 if s.is_empty() { "'_".to_string() } else { s }
1096 }
1097
1098 for (i, (arg1, arg2)) in sub1.iter().zip(sub2).enumerate().take(len) {
1099 self.push_comma(&mut values.0, &mut values.1, i);
1100 match arg1.kind() {
1101 ty::GenericArgKind::Lifetime(l1) => {
1118 let l1_str = lifetime_display(l1);
1119 let l2 = arg2.expect_region();
1120 let l2_str = lifetime_display(l2);
1121 if l1 != l2 {
1122 values.0.push_highlighted(l1_str);
1123 values.1.push_highlighted(l2_str);
1124 } else if l1.is_bound() || self.tcx.sess.opts.verbose {
1125 values.0.push_normal(l1_str);
1126 values.1.push_normal(l2_str);
1127 } else {
1128 values.0.push_normal("'_");
1129 values.1.push_normal("'_");
1130 }
1131 }
1132 ty::GenericArgKind::Type(ta1) => {
1133 let ta2 = arg2.expect_ty();
1134 if ta1 == ta2 && !self.tcx.sess.opts.verbose {
1135 values.0.push_normal("_");
1136 values.1.push_normal("_");
1137 } else {
1138 recurse(ta1, ta2, &mut values);
1139 }
1140 }
1141 ty::GenericArgKind::Const(ca1) => {
1151 let ca2 = arg2.expect_const();
1152 maybe_highlight(ca1, ca2, &mut values, self.tcx);
1153 }
1154 }
1155 }
1156
1157 if len > 0 {
1160 values.0.push_normal(">");
1161 values.1.push_normal(">");
1162 }
1163 values
1164 } else {
1165 if self.cmp_type_arg(
1171 &mut values.0,
1172 &mut values.1,
1173 path1.clone(),
1174 sub_no_defaults_1,
1175 path2.clone(),
1176 t2,
1177 ) {
1178 return values;
1179 }
1180 if self.cmp_type_arg(
1186 &mut values.1,
1187 &mut values.0,
1188 path2,
1189 sub_no_defaults_2,
1190 path1,
1191 t1,
1192 ) {
1193 return values;
1194 }
1195
1196 let t1_str = t1.to_string();
1203 let t2_str = t2.to_string();
1204 let min_len = t1_str.len().min(t2_str.len());
1205
1206 const SEPARATOR: &str = "::";
1207 let separator_len = SEPARATOR.len();
1208 let split_idx: usize =
1209 iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1210 .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1211 .map(|(mod_str, _)| mod_str.len() + separator_len)
1212 .sum();
1213
1214 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1214",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1214u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["message",
"separator_len", "split_idx", "min_len"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("cmp")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&separator_len)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&split_idx)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&min_len) as
&dyn Value))])
});
} else { ; }
};debug!(?separator_len, ?split_idx, ?min_len, "cmp");
1215
1216 if split_idx >= min_len {
1217 (
1219 DiagStyledString::highlighted(t1_str),
1220 DiagStyledString::highlighted(t2_str),
1221 )
1222 } else {
1223 let (common, uniq1) = t1_str.split_at(split_idx);
1224 let (_, uniq2) = t2_str.split_at(split_idx);
1225 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1225",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1225u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["message", "common",
"uniq1", "uniq2"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("cmp")
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&common) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&uniq1) as
&dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&uniq2) as
&dyn Value))])
});
} else { ; }
};debug!(?common, ?uniq1, ?uniq2, "cmp");
1226
1227 values.0.push_normal(common);
1228 values.0.push_highlighted(uniq1);
1229 values.1.push_normal(common);
1230 values.1.push_highlighted(uniq2);
1231
1232 values
1233 }
1234 }
1235 }
1236
1237 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2)) => {
1239 let mut values = (DiagStyledString::new(), DiagStyledString::new());
1240 cmp_ty_refs(r1, mutbl1, r2, mutbl2, &mut values);
1241 recurse(ref_ty1, ref_ty2, &mut values);
1242 values
1243 }
1244 (&ty::Ref(r1, ref_ty1, mutbl1), _) => {
1246 let mut values = (DiagStyledString::new(), DiagStyledString::new());
1247 push_ref(r1, mutbl1, &mut values.0);
1248 recurse(ref_ty1, t2, &mut values);
1249 values
1250 }
1251 (_, &ty::Ref(r2, ref_ty2, mutbl2)) => {
1252 let mut values = (DiagStyledString::new(), DiagStyledString::new());
1253 push_ref(r2, mutbl2, &mut values.1);
1254 recurse(t1, ref_ty2, &mut values);
1255 values
1256 }
1257
1258 (&ty::Tuple(args1), &ty::Tuple(args2)) if args1.len() == args2.len() => {
1260 let mut values = (DiagStyledString::normal("("), DiagStyledString::normal("("));
1261 let len = args1.len();
1262 for (i, (left, right)) in args1.iter().zip(args2).enumerate() {
1263 self.push_comma(&mut values.0, &mut values.1, i);
1264 recurse(left, right, &mut values);
1265 }
1266 if len == 1 {
1267 values.0.push_normal(",");
1269 values.1.push_normal(",");
1270 }
1271 values.0.push_normal(")");
1272 values.1.push_normal(")");
1273 values
1274 }
1275
1276 (ty::FnDef(did1, args1), ty::FnDef(did2, args2)) => {
1277 let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1).skip_norm_wip();
1278 let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2).skip_norm_wip();
1279 self.cmp_fn_sig(sig1, Some((*did1, Some(args1))), sig2, Some((*did2, Some(args2))))
1280 }
1281
1282 (ty::FnDef(did1, args1), ty::FnPtr(sig_tys2, hdr2)) => {
1283 let sig1 = self.tcx.fn_sig(*did1).instantiate(self.tcx, args1).skip_norm_wip();
1284 self.cmp_fn_sig(sig1, Some((*did1, Some(args1))), sig_tys2.with(*hdr2), None)
1285 }
1286
1287 (ty::FnPtr(sig_tys1, hdr1), ty::FnDef(did2, args2)) => {
1288 let sig2 = self.tcx.fn_sig(*did2).instantiate(self.tcx, args2).skip_norm_wip();
1289 self.cmp_fn_sig(sig_tys1.with(*hdr1), None, sig2, Some((*did2, Some(args2))))
1290 }
1291
1292 (ty::FnPtr(sig_tys1, hdr1), ty::FnPtr(sig_tys2, hdr2)) => {
1293 self.cmp_fn_sig(sig_tys1.with(*hdr1), None, sig_tys2.with(*hdr2), None)
1294 }
1295
1296 _ => {
1297 let mut strs = (DiagStyledString::new(), DiagStyledString::new());
1298 maybe_highlight(t1, t2, &mut strs, self.tcx);
1299 strs
1300 }
1301 }
1302 }
1303
1304 #[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("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1313u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["cause", "values",
"terr", "override_span"],
::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};
let mut iter = meta.fields().iter();
meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&cause)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&values)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&terr)
as &dyn Value)),
(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&::tracing::field::debug(&override_span)
as &dyn 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 compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1424",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1424u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("note_type_err(diag={0:?})",
diag) as &dyn 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 mut values = self.resolve_vars_if_possible(values);
if self.next_trait_solver() {
values =
deeply_normalize_for_diagnostics(self, param_env, 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 } => def_id.into(),
ty::AliasTermKind::InherentTy { def_id } => def_id.into(),
ty::AliasTermKind::OpaqueTy { def_id } => def_id.into(),
ty::AliasTermKind::FreeTy { def_id } => def_id.into(),
ty::AliasTermKind::AnonConst { def_id } => def_id.into(),
ty::AliasTermKind::ProjectionConst { def_id } =>
def_id.into(),
ty::AliasTermKind::FreeConst { def_id } => def_id.into(),
ty::AliasTermKind::InherentConst { def_id } =>
def_id.into(),
};
(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: Span, msg: Cow<'static, str>|
{
if (prefer_label && is_simple_error) ||
&[span] == diag.span.primary_spans() {
diag.span_label(span, msg);
} 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, secondary_msg);
} else {
label_or_note(span, 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, terr.to_string(self.tcx));
} else {
label_or_note(span,
Cow::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1}",
expected, found))
})));
}
} else { label_or_note(span, 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 compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1741",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1741u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("note_type_err: exp_found={0:?}, expected={1:?} found={2:?}",
exp_found, expected, found) as &dyn 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 compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1781",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1781u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("exp_found {0:?} terr {1:?} cause.code {2:?}",
exp_found, terr, cause.code()) as &dyn 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_id !=
CRATE_DEF_ID).then(|| cause.body_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 compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:1834",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(1834u32),
::tracing_core::__macro_support::Option::Some("rustc_trait_selection::error_reporting::infer"),
::tracing_core::field::FieldSet::new(&["diag"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&debug(&diag) as
&dyn Value))])
});
} else { ; }
};
}
}
}#[instrument(level = "debug", skip(self, diag, secondary_span, prefer_label))]
1314 pub fn note_type_err(
1315 &self,
1316 diag: &mut Diag<'_>,
1317 cause: &ObligationCause<'tcx>,
1318 secondary_span: Option<(Span, Cow<'static, str>, bool)>,
1319 mut values: Option<ty::ParamEnvAnd<'tcx, ValuePairs<'tcx>>>,
1320 terr: TypeError<'tcx>,
1321 prefer_label: bool,
1322 override_span: Option<Span>,
1323 ) {
1324 let span = override_span.unwrap_or(cause.span);
1329 if let TypeError::CyclicTy(_) = terr {
1332 values = None;
1333 }
1334 struct OpaqueTypesVisitor<'tcx> {
1335 types: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1336 expected: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1337 found: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1338 ignore_span: Span,
1339 tcx: TyCtxt<'tcx>,
1340 }
1341
1342 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1343 fn visit_expected_found(
1344 tcx: TyCtxt<'tcx>,
1345 expected: impl TypeVisitable<TyCtxt<'tcx>>,
1346 found: impl TypeVisitable<TyCtxt<'tcx>>,
1347 ignore_span: Span,
1348 ) -> Self {
1349 let mut types_visitor = OpaqueTypesVisitor {
1350 types: Default::default(),
1351 expected: Default::default(),
1352 found: Default::default(),
1353 ignore_span,
1354 tcx,
1355 };
1356 expected.visit_with(&mut types_visitor);
1360 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1361 found.visit_with(&mut types_visitor);
1362 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1363 types_visitor
1364 }
1365
1366 fn report(&self, err: &mut Diag<'_>) {
1367 self.add_labels_for_types(err, "expected", &self.expected);
1368 self.add_labels_for_types(err, "found", &self.found);
1369 }
1370
1371 fn add_labels_for_types(
1372 &self,
1373 err: &mut Diag<'_>,
1374 target: &str,
1375 types: &FxIndexMap<TyCategory, FxIndexSet<Span>>,
1376 ) {
1377 for (kind, values) in types.iter() {
1378 let count = values.len();
1379 for &sp in values {
1380 err.span_label(
1381 sp,
1382 format!(
1383 "{}{} {:#}{}",
1384 if count == 1 { "the " } else { "one of the " },
1385 target,
1386 kind,
1387 pluralize!(count),
1388 ),
1389 );
1390 }
1391 }
1392 }
1393 }
1394
1395 impl<'tcx> ty::TypeVisitor<TyCtxt<'tcx>> for OpaqueTypesVisitor<'tcx> {
1396 fn visit_ty(&mut self, t: Ty<'tcx>) {
1397 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1398 let span = self.tcx.def_span(def_id);
1399 if !self.ignore_span.overlaps(span)
1415 && !span.is_desugaring(DesugaringKind::Async)
1416 {
1417 self.types.entry(kind).or_default().insert(span);
1418 }
1419 }
1420 t.super_visit_with(self)
1421 }
1422 }
1423
1424 debug!("note_type_err(diag={:?})", diag);
1425 enum Mismatch<'a> {
1426 Variable(ty::error::ExpectedFound<Ty<'a>>),
1427 Fixed(&'static str),
1428 }
1429 let (expected_found, exp_found, is_simple_error, values, param_env) = match values {
1430 None => (None, Mismatch::Fixed("type"), false, None, None),
1431 Some(ty::ParamEnvAnd { param_env, value: values }) => {
1432 let mut values = self.resolve_vars_if_possible(values);
1433 if self.next_trait_solver() {
1434 values = deeply_normalize_for_diagnostics(self, param_env, values);
1435 }
1436 let (is_simple_error, exp_found) = match values {
1437 ValuePairs::Terms(ExpectedFound { expected, found }) => {
1438 match (expected.kind(), found.kind()) {
1439 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
1440 let is_simple_err =
1441 expected.is_simple_text() && found.is_simple_text();
1442 OpaqueTypesVisitor::visit_expected_found(
1443 self.tcx, expected, found, span,
1444 )
1445 .report(diag);
1446
1447 (
1448 is_simple_err,
1449 Mismatch::Variable(ExpectedFound { expected, found }),
1450 )
1451 }
1452 (ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
1453 (false, Mismatch::Fixed("constant"))
1454 }
1455 _ => (false, Mismatch::Fixed("type")),
1456 }
1457 }
1458 ValuePairs::PolySigs(ExpectedFound { expected, found }) => {
1459 OpaqueTypesVisitor::visit_expected_found(self.tcx, expected, found, span)
1460 .report(diag);
1461 (false, Mismatch::Fixed("signature"))
1462 }
1463 ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed("trait")),
1464 ValuePairs::Aliases(ExpectedFound { expected, .. }) => {
1465 let def_id = match expected.kind {
1466 ty::AliasTermKind::ProjectionTy { def_id } => def_id.into(),
1467 ty::AliasTermKind::InherentTy { def_id } => def_id.into(),
1468 ty::AliasTermKind::OpaqueTy { def_id } => def_id.into(),
1469 ty::AliasTermKind::FreeTy { def_id } => def_id.into(),
1470 ty::AliasTermKind::AnonConst { def_id } => def_id.into(),
1471 ty::AliasTermKind::ProjectionConst { def_id } => def_id.into(),
1472 ty::AliasTermKind::FreeConst { def_id } => def_id.into(),
1473 ty::AliasTermKind::InherentConst { def_id } => def_id.into(),
1474 };
1475 (false, Mismatch::Fixed(self.tcx.def_descr(def_id)))
1476 }
1477 ValuePairs::Regions(_) => (false, Mismatch::Fixed("lifetime")),
1478 ValuePairs::ExistentialTraitRef(_) => {
1479 (false, Mismatch::Fixed("existential trait ref"))
1480 }
1481 ValuePairs::ExistentialProjection(_) => {
1482 (false, Mismatch::Fixed("existential projection"))
1483 }
1484 };
1485 let Some(vals) = self.values_str(values, cause, diag.long_ty_path()) else {
1486 diag.downgrade_to_delayed_bug();
1490 return;
1491 };
1492 (Some(vals), exp_found, is_simple_error, Some(values), Some(param_env))
1493 }
1494 };
1495
1496 let mut label_or_note = |span: Span, msg: Cow<'static, str>| {
1497 if (prefer_label && is_simple_error) || &[span] == diag.span.primary_spans() {
1498 diag.span_label(span, msg);
1499 } else {
1500 diag.span_note(span, msg);
1501 }
1502 };
1503 if let Some((secondary_span, secondary_msg, swap_secondary_and_primary)) = secondary_span {
1504 if swap_secondary_and_primary {
1505 let terr = if let Some(infer::ValuePairs::Terms(ExpectedFound {
1506 expected, ..
1507 })) = values
1508 {
1509 Cow::from(format!("expected this to be `{expected}`"))
1510 } else {
1511 terr.to_string(self.tcx)
1512 };
1513 label_or_note(secondary_span, terr);
1514 label_or_note(span, secondary_msg);
1515 } else {
1516 label_or_note(span, terr.to_string(self.tcx));
1517 label_or_note(secondary_span, secondary_msg);
1518 }
1519 } else if let Some(values) = values
1520 && let Some((e, f)) = values.ty()
1521 && let TypeError::ArgumentSorts(..) | TypeError::Sorts(_) = terr
1522 {
1523 let e = self.tcx.erase_and_anonymize_regions(e);
1524 let f = self.tcx.erase_and_anonymize_regions(f);
1525 let expected = with_forced_trimmed_paths!(e.sort_string(self.tcx));
1526 let found = with_forced_trimmed_paths!(f.sort_string(self.tcx));
1527 if expected == found {
1528 label_or_note(span, terr.to_string(self.tcx));
1529 } else {
1530 label_or_note(span, Cow::from(format!("expected {expected}, found {found}")));
1531 }
1532 } else {
1533 label_or_note(span, terr.to_string(self.tcx));
1534 }
1535
1536 if let Some(param_env) = param_env {
1537 self.note_field_shadowed_by_private_candidate_in_cause(diag, cause, param_env);
1538 }
1539
1540 if self.check_and_note_conflicting_crates(diag, terr) {
1541 return;
1542 }
1543
1544 if let Some((expected, found)) = expected_found {
1545 let (expected_label, found_label, exp_found) = match exp_found {
1546 Mismatch::Variable(ef) => (
1547 ef.expected.prefix_string(self.tcx),
1548 ef.found.prefix_string(self.tcx),
1549 Some(ef),
1550 ),
1551 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1552 };
1553
1554 enum Similar<'tcx> {
1555 Adts { expected: ty::AdtDef<'tcx>, found: ty::AdtDef<'tcx> },
1556 PrimitiveFound { expected: ty::AdtDef<'tcx>, found: Ty<'tcx> },
1557 PrimitiveExpected { expected: Ty<'tcx>, found: ty::AdtDef<'tcx> },
1558 }
1559
1560 let similarity = |ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>| {
1561 if let ty::Adt(expected, _) = expected.kind()
1562 && let Some(primitive) = found.primitive_symbol()
1563 {
1564 let path = self.tcx.def_path(expected.did()).data;
1565 let name = path.last().unwrap().data.get_opt_name();
1566 if name == Some(primitive) {
1567 return Some(Similar::PrimitiveFound { expected: *expected, found });
1568 }
1569 } else if let Some(primitive) = expected.primitive_symbol()
1570 && let ty::Adt(found, _) = found.kind()
1571 {
1572 let path = self.tcx.def_path(found.did()).data;
1573 let name = path.last().unwrap().data.get_opt_name();
1574 if name == Some(primitive) {
1575 return Some(Similar::PrimitiveExpected { expected, found: *found });
1576 }
1577 } else if let ty::Adt(expected, _) = expected.kind()
1578 && let ty::Adt(found, _) = found.kind()
1579 {
1580 if !expected.did().is_local() && expected.did().krate == found.did().krate {
1581 return None;
1585 }
1586 let f_path = self.tcx.def_path(found.did()).data;
1587 let e_path = self.tcx.def_path(expected.did()).data;
1588
1589 if let (Some(e_last), Some(f_last)) = (e_path.last(), f_path.last())
1590 && e_last == f_last
1591 {
1592 return Some(Similar::Adts { expected: *expected, found: *found });
1593 }
1594 }
1595 None
1596 };
1597
1598 match terr {
1599 TypeError::Sorts(values) if let Some(s) = similarity(values) => {
1601 let diagnose_primitive =
1602 |prim: Ty<'tcx>, shadow: Ty<'tcx>, defid: DefId, diag: &mut Diag<'_>| {
1603 let name = shadow.sort_string(self.tcx);
1604 diag.note(format!(
1605 "`{prim}` and {name} have similar names, but are actually distinct types"
1606 ));
1607 diag.note(format!(
1608 "one `{prim}` is a primitive defined by the language",
1609 ));
1610 let def_span = self.tcx.def_span(defid);
1611 let msg = if defid.is_local() {
1612 format!("the other {name} is defined in the current crate")
1613 } else {
1614 let crate_name = self.tcx.crate_name(defid.krate);
1615 format!("the other {name} is defined in crate `{crate_name}`")
1616 };
1617 diag.span_note(def_span, msg);
1618 };
1619
1620 let diagnose_adts =
1621 |expected_adt: ty::AdtDef<'tcx>,
1622 found_adt: ty::AdtDef<'tcx>,
1623 diag: &mut Diag<'_>| {
1624 let found_name = values.found.sort_string(self.tcx);
1625 let expected_name = values.expected.sort_string(self.tcx);
1626
1627 let found_defid = found_adt.did();
1628 let expected_defid = expected_adt.did();
1629
1630 diag.note(format!("{found_name} and {expected_name} have similar names, but are actually distinct types"));
1631 for (defid, name) in
1632 [(found_defid, found_name), (expected_defid, expected_name)]
1633 {
1634 let def_span = self.tcx.def_span(defid);
1635
1636 let msg = if found_defid.is_local() && expected_defid.is_local() {
1637 let module = self
1638 .tcx
1639 .parent_module_from_def_id(defid.expect_local())
1640 .to_def_id();
1641 let module_name =
1642 self.tcx.def_path(module).to_string_no_crate_verbose();
1643 format!(
1644 "{name} is defined in module `crate{module_name}` of the current crate"
1645 )
1646 } else if defid.is_local() {
1647 format!("{name} is defined in the current crate")
1648 } else {
1649 let crate_name = self.tcx.crate_name(defid.krate);
1650 format!("{name} is defined in crate `{crate_name}`")
1651 };
1652 diag.span_note(def_span, msg);
1653 }
1654 };
1655
1656 match s {
1657 Similar::Adts { expected, found } => diagnose_adts(expected, found, diag),
1658 Similar::PrimitiveFound { expected, found: prim } => {
1659 diagnose_primitive(prim, values.expected, expected.did(), diag)
1660 }
1661 Similar::PrimitiveExpected { expected: prim, found } => {
1662 diagnose_primitive(prim, values.found, found.did(), diag)
1663 }
1664 }
1665 }
1666 TypeError::Sorts(values) => {
1667 let extra = expected == found
1668 && values.expected.sort_string(self.tcx)
1672 != values.found.sort_string(self.tcx);
1673 let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1674 (true, ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. })) => {
1675 let sm = self.tcx.sess.source_map();
1676 let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1677 DiagStyledString::normal(format!(
1678 " (opaque type at <{}:{}:{}>)",
1679 sm.filename_for_diagnostics(&pos.file.name),
1680 pos.line,
1681 pos.col.to_usize() + 1,
1682 ))
1683 }
1684 (
1685 true,
1686 &ty::Alias(_, ty::AliasTy { kind: ty::Projection { def_id }, .. }),
1687 ) if self.tcx.is_impl_trait_in_trait(def_id) => {
1688 let sm = self.tcx.sess.source_map();
1689 let pos = sm.lookup_char_pos(self.tcx.def_span(def_id).lo());
1690 DiagStyledString::normal(format!(
1691 " (trait associated opaque type at <{}:{}:{}>)",
1692 sm.filename_for_diagnostics(&pos.file.name),
1693 pos.line,
1694 pos.col.to_usize() + 1,
1695 ))
1696 }
1697 (true, _) => {
1698 let mut s = DiagStyledString::normal(" (");
1699 s.push_highlighted(ty.sort_string(self.tcx));
1700 s.push_normal(")");
1701 s
1702 }
1703 (false, _) => DiagStyledString::normal(""),
1704 };
1705 if !(values.expected.is_simple_text() && values.found.is_simple_text())
1706 || (exp_found.is_some_and(|ef| {
1707 if !ef.expected.is_ty_or_numeric_infer() {
1712 ef.expected != values.expected
1713 } else if !ef.found.is_ty_or_numeric_infer() {
1714 ef.found != values.found
1715 } else {
1716 false
1717 }
1718 }))
1719 {
1720 if let Some(ExpectedFound { found: found_ty, .. }) = exp_found
1721 && !self.tcx.ty_is_opaque_future(found_ty)
1722 {
1723 diag.note_expected_found_extra(
1730 &expected_label,
1731 expected,
1732 &found_label,
1733 found,
1734 sort_string(values.expected),
1735 sort_string(values.found),
1736 );
1737 }
1738 }
1739 }
1740 _ => {
1741 debug!(
1742 "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1743 exp_found, expected, found
1744 );
1745 if !is_simple_error || terr.must_include_note() {
1746 diag.note_expected_found(&expected_label, expected, &found_label, found);
1747
1748 if let Some(ty::Closure(_, args)) =
1749 exp_found.map(|expected_type_found| expected_type_found.found.kind())
1750 {
1751 diag.highlighted_note(vec![
1752 StringPart::normal("closure has signature: `"),
1753 StringPart::highlighted(
1754 self.tcx
1755 .signature_unclosure(
1756 args.as_closure().sig(),
1757 rustc_hir::Safety::Safe,
1758 )
1759 .to_string(),
1760 ),
1761 StringPart::normal("`"),
1762 ]);
1763 }
1764 }
1765 }
1766 }
1767 }
1768 let exp_found = match exp_found {
1769 Mismatch::Variable(exp_found) => Some(exp_found),
1770 Mismatch::Fixed(_) => None,
1771 };
1772 let exp_found = match terr {
1773 ty::error::TypeError::Sorts(terr)
1775 if exp_found.is_some_and(|ef| terr.found == ef.found) =>
1776 {
1777 Some(terr)
1778 }
1779 _ => exp_found,
1780 };
1781 debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
1782 if let Some(exp_found) = exp_found {
1783 let should_suggest_fixes =
1784 if let ObligationCauseCode::Pattern { root_ty, .. } = cause.code() {
1785 self.same_type_modulo_infer(*root_ty, exp_found.expected)
1788 } else {
1789 true
1790 };
1791
1792 if should_suggest_fixes
1796 && !matches!(terr, TypeError::RegionsInsufficientlyPolymorphic(..))
1797 {
1798 self.suggest_tuple_pattern(cause, &exp_found, diag);
1799 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1800 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1801 self.suggest_function_pointers(cause, span, &exp_found, terr, diag);
1802 self.suggest_turning_stmt_into_expr(cause, &exp_found, diag);
1803 }
1804 }
1805
1806 let body_owner_def_id = (cause.body_id != CRATE_DEF_ID).then(|| cause.body_id.to_def_id());
1807 self.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id);
1808 if let Some(exp_found) = exp_found
1809 && let exp_found = TypeError::Sorts(exp_found)
1810 && exp_found != terr
1811 {
1812 self.note_and_explain_type_err(diag, exp_found, cause, span, body_owner_def_id);
1813 }
1814
1815 if let Some(ValuePairs::TraitRefs(exp_found)) = values
1816 && let ty::Closure(def_id, _) = exp_found.expected.self_ty().kind()
1817 && let Some(def_id) = def_id.as_local()
1818 && terr.involves_regions()
1819 {
1820 let span = self.tcx.def_span(def_id);
1821 diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1822 self.suggest_for_all_lifetime_closure(
1823 span,
1824 self.tcx.hir_node_by_def_id(def_id),
1825 &exp_found,
1826 diag,
1827 );
1828 }
1829
1830 self.note_error_origin(diag, cause, exp_found, terr, param_env);
1833
1834 debug!(?diag);
1835 }
1836
1837 pub(crate) fn type_error_additional_suggestions(
1838 &self,
1839 trace: &TypeTrace<'tcx>,
1840 terr: TypeError<'tcx>,
1841 long_ty_path: &mut Option<PathBuf>,
1842 ) -> Vec<TypeErrorAdditionalDiags> {
1843 let mut suggestions = Vec::new();
1844 let span = trace.cause.span;
1845 let values = self.resolve_vars_if_possible(trace.values);
1846 if let Some((expected, found)) = values.ty() {
1847 match (expected.kind(), found.kind()) {
1848 (ty::Tuple(_), ty::Tuple(_)) => {}
1849 (ty::Tuple(fields), _) => {
1853 suggestions.extend(self.suggest_wrap_to_build_a_tuple(span, found, fields))
1854 }
1855 (ty::Uint(ty::UintTy::U8), ty::Char) => {
1859 if let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span)
1860 && let Some(code) = code.strip_circumfix('\'', '\'')
1861 && !code.starts_with("\\u")
1863 && code.chars().next().is_some_and(|c| c.is_ascii())
1865 {
1866 suggestions.push(TypeErrorAdditionalDiags::MeantByteLiteral {
1867 span,
1868 code: escape_literal(code),
1869 })
1870 }
1871 }
1872 (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
1876 if let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span)
1877 && let Some(code) = code.strip_circumfix('"', '"')
1878 && code.chars().count() == 1
1879 {
1880 suggestions.push(TypeErrorAdditionalDiags::MeantCharLiteral {
1881 span,
1882 code: escape_literal(code),
1883 })
1884 }
1885 }
1886 (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
1889 if let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span)
1890 && code.starts_with("'")
1891 && code.ends_with("'")
1892 {
1893 suggestions.push(TypeErrorAdditionalDiags::MeantStrLiteral {
1894 start: span.with_hi(span.lo() + BytePos(1)),
1895 end: span.with_lo(span.hi() - BytePos(1)),
1896 });
1897 }
1898 }
1899 (ty::Bool, ty::Tuple(list)) => {
1902 if list.len() == 0 {
1903 suggestions.extend(self.suggest_let_for_letchains(&trace.cause, span));
1904 }
1905 }
1906 (ty::Array(_, _), ty::Array(_, _)) => {
1907 suggestions.extend(self.suggest_specify_actual_length(terr, trace, span))
1908 }
1909 _ => {}
1910 }
1911 }
1912 let code = trace.cause.code();
1913 if let &(ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause {
1914 source, ..
1915 })
1916 | ObligationCauseCode::BlockTailExpression(.., source)) = code
1917 && let hir::MatchSource::TryDesugar(_) = source
1918 && let Some((expected_ty, found_ty)) =
1919 self.values_str(trace.values, &trace.cause, long_ty_path)
1920 {
1921 suggestions.push(TypeErrorAdditionalDiags::TryCannotConvert {
1922 found: found_ty.content(),
1923 expected: expected_ty.content(),
1924 });
1925 }
1926 suggestions
1927 }
1928
1929 fn suggest_specify_actual_length(
1930 &self,
1931 terr: TypeError<'tcx>,
1932 trace: &TypeTrace<'tcx>,
1933 span: Span,
1934 ) -> Option<TypeErrorAdditionalDiags> {
1935 let TypeError::ArraySize(sz) = terr else {
1936 return None;
1937 };
1938 let tykind = match self.tcx.hir_node_by_def_id(trace.cause.body_id) {
1939 hir::Node::Item(hir::Item {
1940 kind: hir::ItemKind::Fn { body: body_id, .. }, ..
1941 }) => {
1942 let body = self.tcx.hir_body(*body_id);
1943 struct LetVisitor {
1944 span: Span,
1945 }
1946 impl<'v> Visitor<'v> for LetVisitor {
1947 type Result = ControlFlow<&'v hir::TyKind<'v>>;
1948 fn visit_stmt(&mut self, s: &'v hir::Stmt<'v>) -> Self::Result {
1949 if let hir::Stmt {
1952 kind:
1953 hir::StmtKind::Let(hir::LetStmt {
1954 init: Some(hir::Expr { span: init_span, .. }),
1955 ty: Some(array_ty),
1956 ..
1957 }),
1958 ..
1959 } = s
1960 && init_span == &self.span
1961 {
1962 ControlFlow::Break(&array_ty.peel_refs().kind)
1963 } else {
1964 ControlFlow::Continue(())
1965 }
1966 }
1967 }
1968 LetVisitor { span }.visit_body(body).break_value()
1969 }
1970 hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(_, _, ty, _), .. }) => {
1971 Some(&ty.peel_refs().kind)
1972 }
1973 _ => None,
1974 };
1975 if let Some(tykind) = tykind
1976 && let hir::TyKind::Array(_, length_arg) = tykind
1977 && let Some(length_val) = sz.found.try_to_target_usize(self.tcx)
1978 {
1979 Some(TypeErrorAdditionalDiags::ConsiderSpecifyingLength {
1980 span: length_arg.span,
1981 length: length_val,
1982 })
1983 } else {
1984 None
1985 }
1986 }
1987
1988 fn check_on_type_error_attribute(
1989 &self,
1990 expected_ty: Ty<'tcx>,
1991 found_ty: Ty<'tcx>,
1992 ) -> ThinVec<String> {
1993 let mut seen = FxHashSet::default();
1994 let mut unique_notes: ThinVec<String> = ThinVec::new();
1995
1996 if let ty::Adt(item_def, args) = found_ty.kind() {
1998 if let Some(Some(directive)) =
1999 {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(item_def.did(),
&self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(OnTypeError { directive, .. })
=> {
break 'done Some(directive);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.tcx, item_def.did(), OnTypeError { directive, .. } => directive)
2000 {
2001 let notes = self.format_on_type_error_notes(
2002 directive,
2003 args,
2004 item_def.clone(),
2005 expected_ty,
2006 found_ty,
2007 );
2008
2009 for note in notes {
2010 if seen.insert(note.clone()) {
2011 unique_notes.push(note);
2012 }
2013 }
2014 }
2015 }
2016
2017 if let ty::Adt(item_def, args) = expected_ty.kind() {
2019 if let Some(Some(directive)) =
2020 {
{
'done:
{
for i in
::rustc_hir::attrs::HasAttrs::get_attrs(item_def.did(),
&self.tcx) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(OnTypeError { directive, .. })
=> {
break 'done Some(directive);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(self.tcx, item_def.did(), OnTypeError { directive, .. } => directive)
2021 {
2022 let notes = self.format_on_type_error_notes(
2023 directive,
2024 args,
2025 item_def.clone(),
2026 expected_ty,
2027 found_ty,
2028 );
2029
2030 for note in notes {
2031 if seen.insert(note.clone()) {
2032 unique_notes.push(note);
2033 }
2034 }
2035 }
2036 }
2037
2038 unique_notes
2039 }
2040
2041 fn format_on_type_error_notes(
2042 &self,
2043 directive: &Directive,
2044 args: &ty::GenericArgsRef<'tcx>,
2045 item_def: ty::AdtDef<'tcx>,
2046 expected_ty: Ty<'tcx>,
2047 found_ty: Ty<'tcx>,
2048 ) -> ThinVec<String> {
2049 let item_name = self.tcx.item_name(item_def.did()).to_string();
2050 let generic_args: Vec<_> = self
2051 .tcx
2052 .generics_of(item_def.did())
2053 .own_params
2054 .iter()
2055 .filter_map(|param| Some((param.name, args[param.index as usize].to_string())))
2056 .collect();
2057
2058 let format_args = FormatArgs {
2059 this: item_name,
2060 generic_args,
2061 found: found_ty.to_string(),
2062 expected: expected_ty.to_string(),
2063 ..
2064 };
2065 let CustomDiagnostic { notes, .. } = directive.eval(None, &format_args);
2066
2067 notes.into()
2068 }
2069
2070 pub fn report_and_explain_type_error(
2071 &self,
2072 trace: TypeTrace<'tcx>,
2073 param_env: ty::ParamEnv<'tcx>,
2074 terr: TypeError<'tcx>,
2075 ) -> Diag<'a> {
2076 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs:2076",
"rustc_trait_selection::error_reporting::infer",
::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/error_reporting/infer/mod.rs"),
::tracing_core::__macro_support::Option::Some(2076u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("report_and_explain_type_error(trace={0:?}, terr={1:?})",
trace, terr) as &dyn Value))])
});
} else { ; }
};debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
2077
2078 let span = trace.cause.span;
2079 let mut path = None;
2080
2081 let on_type_error_notes = if let Some((expected_ty, found_ty)) = trace.values.ty() {
2083 self.check_on_type_error_attribute(expected_ty, found_ty)
2084 } else {
2085 ThinVec::new()
2086 };
2087
2088 let failure_code = trace.cause.as_failure_code_diag(
2089 terr,
2090 span,
2091 self.type_error_additional_suggestions(&trace, terr, &mut path),
2092 );
2093 let mut diag = self.dcx().create_err(failure_code);
2094 *diag.long_ty_path() = path;
2095
2096 for note in on_type_error_notes {
2098 diag.note(note);
2099 }
2100
2101 self.note_type_err(
2102 &mut diag,
2103 &trace.cause,
2104 None,
2105 Some(param_env.and(trace.values)),
2106 terr,
2107 false,
2108 None,
2109 );
2110 diag
2111 }
2112
2113 fn suggest_wrap_to_build_a_tuple(
2114 &self,
2115 span: Span,
2116 found: Ty<'tcx>,
2117 expected_fields: &List<Ty<'tcx>>,
2118 ) -> Option<TypeErrorAdditionalDiags> {
2119 let [expected_tup_elem] = expected_fields[..] else { return None };
2120
2121 if !self.same_type_modulo_infer(expected_tup_elem, found) {
2122 return None;
2123 }
2124
2125 let Ok(code) = self.tcx.sess.source_map().span_to_snippet(span) else { return None };
2126
2127 let sugg = if code.starts_with('(') && code.ends_with(')') {
2128 let before_close = span.hi() - BytePos::from_u32(1);
2129 TypeErrorAdditionalDiags::TupleOnlyComma {
2130 span: span.with_hi(before_close).shrink_to_hi(),
2131 }
2132 } else {
2133 TypeErrorAdditionalDiags::TupleAlsoParentheses {
2134 span_low: span.shrink_to_lo(),
2135 span_high: span.shrink_to_hi(),
2136 }
2137 };
2138 Some(sugg)
2139 }
2140
2141 fn values_str(
2142 &self,
2143 values: ValuePairs<'tcx>,
2144 cause: &ObligationCause<'tcx>,
2145 long_ty_path: &mut Option<PathBuf>,
2146 ) -> Option<(DiagStyledString, DiagStyledString)> {
2147 match values {
2148 ValuePairs::Regions(exp_found) => self.expected_found_str(exp_found),
2149 ValuePairs::Terms(exp_found) => self.expected_found_str_term(exp_found, long_ty_path),
2150 ValuePairs::Aliases(exp_found) => self.expected_found_str(exp_found),
2151 ValuePairs::ExistentialTraitRef(exp_found) => self.expected_found_str(exp_found),
2152 ValuePairs::ExistentialProjection(exp_found) => self.expected_found_str(exp_found),
2153 ValuePairs::TraitRefs(exp_found) => {
2154 let pretty_exp_found = ty::error::ExpectedFound {
2155 expected: exp_found.expected.print_trait_sugared(),
2156 found: exp_found.found.print_trait_sugared(),
2157 };
2158 match self.expected_found_str(pretty_exp_found) {
2159 Some((expected, found)) if expected == found => {
2160 self.expected_found_str(exp_found)
2161 }
2162 ret => ret,
2163 }
2164 }
2165 ValuePairs::PolySigs(exp_found) => {
2166 let exp_found = self.resolve_vars_if_possible(exp_found);
2167 if exp_found.references_error() {
2168 return None;
2169 }
2170 let (fn_def1, fn_def2) = if let ObligationCauseCode::CompareImplItem {
2171 impl_item_def_id,
2172 trait_item_def_id,
2173 ..
2174 } = *cause.code()
2175 {
2176 (Some((trait_item_def_id, None)), Some((impl_item_def_id.to_def_id(), None)))
2177 } else {
2178 (None, None)
2179 };
2180
2181 Some(self.cmp_fn_sig(exp_found.expected, fn_def1, exp_found.found, fn_def2))
2182 }
2183 }
2184 }
2185
2186 fn expected_found_str_term(
2187 &self,
2188 exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2189 long_ty_path: &mut Option<PathBuf>,
2190 ) -> Option<(DiagStyledString, DiagStyledString)> {
2191 let exp_found = self.resolve_vars_if_possible(exp_found);
2192 if exp_found.references_error() {
2193 return None;
2194 }
2195
2196 Some(match (exp_found.expected.kind(), exp_found.found.kind()) {
2197 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
2198 let (mut exp, mut fnd) = self.cmp(expected, found);
2199 let len = self.tcx.sess.diagnostic_width() + 40;
2203 let exp_s = exp.content();
2204 let fnd_s = fnd.content();
2205 if exp_s.len() > len {
2206 let exp_s = self.tcx.short_string(expected, long_ty_path);
2207 exp = DiagStyledString::highlighted(exp_s);
2208 }
2209 if fnd_s.len() > len {
2210 let fnd_s = self.tcx.short_string(found, long_ty_path);
2211 fnd = DiagStyledString::highlighted(fnd_s);
2212 }
2213 (exp, fnd)
2214 }
2215 _ => (
2216 DiagStyledString::highlighted(exp_found.expected.to_string()),
2217 DiagStyledString::highlighted(exp_found.found.to_string()),
2218 ),
2219 })
2220 }
2221
2222 fn expected_found_str<T: fmt::Display + TypeFoldable<TyCtxt<'tcx>>>(
2224 &self,
2225 exp_found: ty::error::ExpectedFound<T>,
2226 ) -> Option<(DiagStyledString, DiagStyledString)> {
2227 let exp_found = self.resolve_vars_if_possible(exp_found);
2228 if exp_found.references_error() {
2229 return None;
2230 }
2231
2232 Some((
2233 DiagStyledString::highlighted(exp_found.expected.to_string()),
2234 DiagStyledString::highlighted(exp_found.found.to_string()),
2235 ))
2236 }
2237
2238 pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2242 span.is_desugaring(DesugaringKind::QuestionMark)
2243 && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2244 }
2245
2246 pub fn same_type_modulo_infer<T: relate::Relate<TyCtxt<'tcx>>>(&self, a: T, b: T) -> bool {
2253 let (a, b) = self.resolve_vars_if_possible((a, b));
2254 SameTypeModuloInfer(self).relate(a, b).is_ok()
2255 }
2256}
2257
2258struct SameTypeModuloInfer<'a, 'tcx>(&'a InferCtxt<'tcx>);
2259
2260impl<'tcx> TypeRelation<TyCtxt<'tcx>> for SameTypeModuloInfer<'_, 'tcx> {
2261 fn cx(&self) -> TyCtxt<'tcx> {
2262 self.0.tcx
2263 }
2264
2265 fn relate_ty_args(
2266 &mut self,
2267 a_ty: Ty<'tcx>,
2268 _: Ty<'tcx>,
2269 _: DefId,
2270 a_args: ty::GenericArgsRef<'tcx>,
2271 b_args: ty::GenericArgsRef<'tcx>,
2272 _: impl FnOnce(ty::GenericArgsRef<'tcx>) -> Ty<'tcx>,
2273 ) -> RelateResult<'tcx, Ty<'tcx>> {
2274 relate::relate_args_invariantly(self, a_args, b_args)?;
2275 Ok(a_ty)
2276 }
2277
2278 fn relate_with_variance<T: relate::Relate<TyCtxt<'tcx>>>(
2279 &mut self,
2280 _variance: ty::Variance,
2281 _info: ty::VarianceDiagInfo<TyCtxt<'tcx>>,
2282 a: T,
2283 b: T,
2284 ) -> relate::RelateResult<'tcx, T> {
2285 self.relate(a, b)
2286 }
2287
2288 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
2289 match (a.kind(), b.kind()) {
2290 (ty::Int(_) | ty::Uint(_), ty::Infer(ty::InferTy::IntVar(_)))
2291 | (
2292 ty::Infer(ty::InferTy::IntVar(_)),
2293 ty::Int(_) | ty::Uint(_) | ty::Infer(ty::InferTy::IntVar(_)),
2294 )
2295 | (ty::Float(_), ty::Infer(ty::InferTy::FloatVar(_)))
2296 | (
2297 ty::Infer(ty::InferTy::FloatVar(_)),
2298 ty::Float(_) | ty::Infer(ty::InferTy::FloatVar(_)),
2299 )
2300 | (ty::Infer(ty::InferTy::TyVar(_)), _)
2301 | (_, ty::Infer(ty::InferTy::TyVar(_))) => Ok(a),
2302 (ty::Infer(_), _) | (_, ty::Infer(_)) => Err(TypeError::Mismatch),
2303 _ => relate::structurally_relate_tys(self, a, b),
2304 }
2305 }
2306
2307 fn regions(
2308 &mut self,
2309 a: ty::Region<'tcx>,
2310 b: ty::Region<'tcx>,
2311 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
2312 if (a.is_var() && b.is_free())
2313 || (b.is_var() && a.is_free())
2314 || (a.is_var() && b.is_var())
2315 || a == b
2316 {
2317 Ok(a)
2318 } else {
2319 Err(TypeError::Mismatch)
2320 }
2321 }
2322
2323 fn binders<T>(
2324 &mut self,
2325 a: ty::Binder<'tcx, T>,
2326 b: ty::Binder<'tcx, T>,
2327 ) -> relate::RelateResult<'tcx, ty::Binder<'tcx, T>>
2328 where
2329 T: relate::Relate<TyCtxt<'tcx>>,
2330 {
2331 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
2332 }
2333
2334 fn consts(
2335 &mut self,
2336 a: ty::Const<'tcx>,
2337 _b: ty::Const<'tcx>,
2338 ) -> relate::RelateResult<'tcx, ty::Const<'tcx>> {
2339 Ok(a)
2342 }
2343}
2344
2345pub enum FailureCode {
2346 Error0317,
2347 Error0580,
2348 Error0308,
2349 Error0644,
2350}
2351
2352impl<'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>)]
2353impl<'tcx> ObligationCause<'tcx> {
2354 fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
2355 match self.code() {
2356 ObligationCauseCode::IfExpressionWithNoElse => FailureCode::Error0317,
2357 ObligationCauseCode::MainFunctionType => FailureCode::Error0580,
2358 ObligationCauseCode::CompareImplItem { .. }
2359 | ObligationCauseCode::MatchExpressionArm(_)
2360 | ObligationCauseCode::IfExpression { .. }
2361 | ObligationCauseCode::LetElse
2362 | ObligationCauseCode::LangFunctionType(_)
2363 | ObligationCauseCode::IntrinsicType
2364 | ObligationCauseCode::MethodReceiver => FailureCode::Error0308,
2365
2366 _ => match terr {
2370 TypeError::CyclicTy(ty)
2371 if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() =>
2372 {
2373 FailureCode::Error0644
2374 }
2375 TypeError::IntrinsicCast | TypeError::ForceInlineCast => FailureCode::Error0308,
2376 _ => FailureCode::Error0308,
2377 },
2378 }
2379 }
2380
2381 fn as_failure_code_diag(
2382 &self,
2383 terr: TypeError<'tcx>,
2384 span: Span,
2385 subdiags: Vec<TypeErrorAdditionalDiags>,
2386 ) -> ObligationCauseFailureCode {
2387 match self.code() {
2388 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2389 ObligationCauseFailureCode::MethodCompat { span, subdiags }
2390 }
2391 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2392 ObligationCauseFailureCode::TypeCompat { span, subdiags }
2393 }
2394 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2395 ObligationCauseFailureCode::ConstCompat { span, subdiags }
2396 }
2397 ObligationCauseCode::BlockTailExpression(.., hir::MatchSource::TryDesugar(_)) => {
2398 ObligationCauseFailureCode::TryCompat { span, subdiags }
2399 }
2400 ObligationCauseCode::MatchExpressionArm(MatchExpressionArmCause { source, .. }) => {
2401 match source {
2402 hir::MatchSource::TryDesugar(_) => {
2403 ObligationCauseFailureCode::TryCompat { span, subdiags }
2404 }
2405 _ => ObligationCauseFailureCode::MatchCompat { span, subdiags },
2406 }
2407 }
2408 ObligationCauseCode::IfExpression { .. } => {
2409 ObligationCauseFailureCode::IfElseDifferent { span, subdiags }
2410 }
2411 ObligationCauseCode::IfExpressionWithNoElse => {
2412 ObligationCauseFailureCode::NoElse { span }
2413 }
2414 ObligationCauseCode::LetElse => {
2415 ObligationCauseFailureCode::NoDiverge { span, subdiags }
2416 }
2417 ObligationCauseCode::MainFunctionType => {
2418 ObligationCauseFailureCode::FnMainCorrectType { span }
2419 }
2420 &ObligationCauseCode::LangFunctionType(lang_item_name) => {
2421 ObligationCauseFailureCode::FnLangCorrectType { span, subdiags, lang_item_name }
2422 }
2423 ObligationCauseCode::IntrinsicType => {
2424 ObligationCauseFailureCode::IntrinsicCorrectType { span, subdiags }
2425 }
2426 ObligationCauseCode::MethodReceiver => {
2427 ObligationCauseFailureCode::MethodCorrectType { span, subdiags }
2428 }
2429
2430 _ => match terr {
2434 TypeError::CyclicTy(ty)
2435 if ty.is_closure() || ty.is_coroutine() || ty.is_coroutine_closure() =>
2436 {
2437 ObligationCauseFailureCode::ClosureSelfref { span }
2438 }
2439 TypeError::ForceInlineCast => {
2440 ObligationCauseFailureCode::CantCoerceForceInline { span, subdiags }
2441 }
2442 TypeError::IntrinsicCast => {
2443 ObligationCauseFailureCode::CantCoerceIntrinsic { span, subdiags }
2444 }
2445 _ => ObligationCauseFailureCode::Generic { span, subdiags },
2446 },
2447 }
2448 }
2449
2450 fn as_requirement_str(&self) -> &'static str {
2451 match self.code() {
2452 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2453 "method type is compatible with trait"
2454 }
2455 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2456 "associated type is compatible with trait"
2457 }
2458 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2459 "const is compatible with trait"
2460 }
2461 ObligationCauseCode::MainFunctionType => "`main` function has the correct type",
2462 ObligationCauseCode::LangFunctionType(_) => "lang item function has the correct type",
2463 ObligationCauseCode::IntrinsicType => "intrinsic has the correct type",
2464 ObligationCauseCode::MethodReceiver => "method receiver has the correct type",
2465 _ => "types are compatible",
2466 }
2467 }
2468}
2469
2470pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
2472
2473impl IntoDiagArg for ObligationCauseAsDiagArg<'_> {
2474 fn into_diag_arg(self, _: &mut Option<std::path::PathBuf>) -> rustc_errors::DiagArgValue {
2475 let kind = match self.0.code() {
2476 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Fn { .. }, .. } => {
2477 "method_compat"
2478 }
2479 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Type { .. }, .. } => {
2480 "type_compat"
2481 }
2482 ObligationCauseCode::CompareImplItem { kind: ty::AssocKind::Const { .. }, .. } => {
2483 "const_compat"
2484 }
2485 ObligationCauseCode::MainFunctionType => "fn_main_correct_type",
2486 ObligationCauseCode::LangFunctionType(_) => "fn_lang_correct_type",
2487 ObligationCauseCode::IntrinsicType => "intrinsic_correct_type",
2488 ObligationCauseCode::MethodReceiver => "method_correct_type",
2489 _ => "other",
2490 }
2491 .into();
2492 rustc_errors::DiagArgValue::Str(kind)
2493 }
2494}
2495
2496#[derive(#[automatically_derived]
impl ::core::clone::Clone for TyCategory {
#[inline]
fn clone(&self) -> TyCategory {
let _: ::core::clone::AssertParamIsClone<hir::CoroutineKind>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for TyCategory { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for TyCategory {
#[inline]
fn eq(&self, other: &TyCategory) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(TyCategory::Coroutine(__self_0),
TyCategory::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) {
let __self_discr = ::core::intrinsics::discriminant_value(self);
::core::hash::Hash::hash(&__self_discr, state);
match self {
TyCategory::Coroutine(__self_0) =>
::core::hash::Hash::hash(__self_0, state),
_ => {}
}
}
}Hash)]
2499pub enum TyCategory {
2500 Closure,
2501 Opaque,
2502 OpaqueFuture,
2503 Coroutine(hir::CoroutineKind),
2504 Foreign,
2505}
2506
2507impl fmt::Display for TyCategory {
2508 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2509 match self {
2510 Self::Closure => "closure".fmt(f),
2511 Self::Opaque => "opaque type".fmt(f),
2512 Self::OpaqueFuture => "future".fmt(f),
2513 Self::Coroutine(gk) => gk.fmt(f),
2514 Self::Foreign => "foreign type".fmt(f),
2515 }
2516 }
2517}
2518
2519impl TyCategory {
2520 pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2521 match *ty.kind() {
2522 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2523 ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, .. }) => {
2524 let kind =
2525 if tcx.ty_is_opaque_future(ty) { Self::OpaqueFuture } else { Self::Opaque };
2526 Some((kind, def_id))
2527 }
2528 ty::Coroutine(def_id, ..) => {
2529 Some((Self::Coroutine(tcx.coroutine_kind(def_id).unwrap()), def_id))
2530 }
2531 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
2532 _ => None,
2533 }
2534 }
2535}