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