1 //! Error Reporting Code for the inference engine
3 //! Because of the way inference, and in particular region inference,
4 //! works, it often happens that errors are not detected until far after
5 //! the relevant line of code has been type-checked. Therefore, there is
6 //! an elaborate system to track why a particular constraint in the
7 //! inference graph arose so that we can explain to the user what gave
8 //! rise to a particular error.
10 //! The system is based around a set of "origin" types. An "origin" is the
11 //! reason that a constraint or inference variable arose. There are
12 //! different "origin" enums for different kinds of constraints/variables
13 //! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
14 //! a span, but also more information so that we can generate a meaningful
17 //! Having a catalog of all the different reasons an error can arise is
18 //! also useful for other reasons, like cross-referencing FAQs etc, though
19 //! we are not really taking advantage of this yet.
21 //! # Region Inference
23 //! Region inference is particularly tricky because it always succeeds "in
24 //! the moment" and simply registers a constraint. Then, at the end, we
25 //! can compute the full graph and report errors, so we need to be able to
26 //! store and later report what gave rise to the conflicting constraints.
30 //! Determining whether `T1 <: T2` often involves a number of subtypes and
31 //! subconstraints along the way. A "TypeTrace" is an extended version
32 //! of an origin that traces the types and other values that were being
33 //! compared. It is not necessarily comprehensive (in fact, at the time of
34 //! this writing it only tracks the root values being compared) but I'd
35 //! like to extend it to include significant "waypoints". For example, if
36 //! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
37 //! <: T4` fails, I'd like the trace to include enough information to say
38 //! "in the 2nd element of the tuple". Similarly, failures when comparing
39 //! arguments or return types in fn types should be able to cite the
40 //! specific position, etc.
44 //! Of course, there is still a LOT of code in typeck that has yet to be
45 //! ported to this system, and which relies on string concatenation at the
46 //! time of error detection.
48 use super::lexical_region_resolve::RegionResolutionError;
49 use super::region_constraints::GenericKind;
50 use super::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePairs};
53 use crate::infer::error_reporting::nice_region_error::find_anon_type::find_anon_type;
54 use crate::infer::ExpectedFound;
55 use crate::traits::error_reporting::report_object_safety_error;
57 IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
61 use rustc_data_structures::fx::{FxIndexMap, FxIndexSet};
62 use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed, IntoDiagnosticArg};
63 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString, MultiSpan};
65 use rustc_hir::def::DefKind;
66 use rustc_hir::def_id::{DefId, LocalDefId};
67 use rustc_hir::lang_items::LangItem;
69 use rustc_middle::dep_graph::DepContext;
70 use rustc_middle::ty::relate::{self, RelateResult, TypeRelation};
71 use rustc_middle::ty::{
72 self, error::TypeError, List, Region, Ty, TyCtxt, TypeFoldable, TypeSuperVisitable,
75 use rustc_span::{sym, symbol::kw, BytePos, DesugaringKind, Pos, Span};
76 use rustc_target::spec::abi;
77 use std::ops::{ControlFlow, Deref};
78 use std::path::PathBuf;
79 use std::{cmp, fmt, iter};
85 pub(crate) mod need_type_info;
86 pub use need_type_info::TypeAnnotationNeeded;
88 pub mod nice_region_error;
90 /// A helper for building type related errors. The `typeck_results`
91 /// field is only populated during an in-progress typeck.
92 /// Get an instance by calling `InferCtxt::err` or `FnCtxt::infer_err`.
93 pub struct TypeErrCtxt<'a, 'tcx> {
94 pub infcx: &'a InferCtxt<'tcx>,
95 pub typeck_results: Option<std::cell::Ref<'a, ty::TypeckResults<'tcx>>>,
96 pub fallback_has_occurred: bool,
98 pub normalize_fn_sig: Box<dyn Fn(ty::PolyFnSig<'tcx>) -> ty::PolyFnSig<'tcx> + 'a>,
101 Box<dyn Fn(Ty<'tcx>) -> Vec<(Ty<'tcx>, Vec<PredicateObligation<'tcx>>)> + 'a>,
104 impl TypeErrCtxt<'_, '_> {
105 /// This is just to avoid a potential footgun of accidentally
106 /// dropping `typeck_results` by calling `InferCtxt::err_ctxt`
107 #[deprecated(note = "you already have a `TypeErrCtxt`")]
109 pub fn err_ctxt(&self) -> ! {
110 bug!("called `err_ctxt` on `TypeErrCtxt`. Try removing the call");
114 impl<'tcx> Deref for TypeErrCtxt<'_, 'tcx> {
115 type Target = InferCtxt<'tcx>;
116 fn deref(&self) -> &InferCtxt<'tcx> {
121 pub(super) fn note_and_explain_region<'tcx>(
123 err: &mut Diagnostic,
125 region: ty::Region<'tcx>,
127 alt_span: Option<Span>,
129 let (description, span) = match *region {
130 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
131 msg_span_from_free_region(tcx, region, alt_span)
134 ty::RePlaceholder(_) => return,
136 // FIXME(#13998) RePlaceholder should probably print like
137 // ReFree rather than dumping Debug output on the user.
139 // We shouldn't really be having unification failures with ReVar
140 // and ReLateBound though.
141 ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
142 (format!("lifetime {:?}", region), alt_span)
146 emit_msg_span(err, prefix, description, span, suffix);
149 fn explain_free_region<'tcx>(
151 err: &mut Diagnostic,
153 region: ty::Region<'tcx>,
156 let (description, span) = msg_span_from_free_region(tcx, region, None);
158 label_msg_span(err, prefix, description, span, suffix);
161 fn msg_span_from_free_region<'tcx>(
163 region: ty::Region<'tcx>,
164 alt_span: Option<Span>,
165 ) -> (String, Option<Span>) {
167 ty::ReEarlyBound(_) | ty::ReFree(_) => {
168 let (msg, span) = msg_span_from_early_bound_and_free_regions(tcx, region);
171 ty::ReStatic => ("the static lifetime".to_owned(), alt_span),
172 _ => bug!("{:?}", region),
176 fn msg_span_from_early_bound_and_free_regions<'tcx>(
178 region: ty::Region<'tcx>,
179 ) -> (String, Span) {
180 let scope = region.free_region_binding_scope(tcx).expect_local();
182 ty::ReEarlyBound(ref br) => {
183 let mut sp = tcx.def_span(scope);
185 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
189 let text = if br.has_name() {
190 format!("the lifetime `{}` as defined here", br.name)
192 "the anonymous lifetime as defined here".to_string()
196 ty::ReFree(ref fr) => {
197 if !fr.bound_region.is_named()
198 && let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region)
200 ("the anonymous lifetime defined here".to_string(), ty.span)
202 match fr.bound_region {
203 ty::BoundRegionKind::BrNamed(_, name) => {
204 let mut sp = tcx.def_span(scope);
206 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
210 let text = if name == kw::UnderscoreLifetime {
211 "the anonymous lifetime as defined here".to_string()
213 format!("the lifetime `{}` as defined here", name)
217 ty::BrAnon(idx, span) => (
218 format!("the anonymous lifetime #{} defined here", idx + 1),
221 None => tcx.def_span(scope)
225 format!("the lifetime `{}` as defined here", region),
236 err: &mut Diagnostic,
242 let message = format!("{}{}{}", prefix, description, suffix);
244 if let Some(span) = span {
245 err.span_note(span, &message);
252 err: &mut Diagnostic,
258 let message = format!("{}{}{}", prefix, description, suffix);
260 if let Some(span) = span {
261 err.span_label(span, &message);
267 #[instrument(level = "trace", skip(tcx))]
268 pub fn unexpected_hidden_region_diagnostic<'tcx>(
272 hidden_region: ty::Region<'tcx>,
273 opaque_ty: ty::OpaqueTypeKey<'tcx>,
274 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
275 let opaque_ty = tcx.mk_opaque(opaque_ty.def_id.to_def_id(), opaque_ty.substs);
276 let mut err = struct_span_err!(
280 "hidden type for `{opaque_ty}` captures lifetime that does not appear in bounds",
283 // Explain the region we are capturing.
284 match *hidden_region {
285 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
286 // Assuming regionck succeeded (*), we ought to always be
287 // capturing *some* region from the fn header, and hence it
288 // ought to be free. So under normal circumstances, we will go
289 // down this path which gives a decent human readable
292 // (*) if not, the `tainted_by_errors` field would be set to
293 // `Some(ErrorGuaranteed)` in any case, so we wouldn't be here at all.
297 &format!("hidden type `{}` captures ", hidden_ty),
301 if let Some(reg_info) = tcx.is_suitable_region(hidden_region) {
302 let fn_returns = tcx.return_type_impl_or_dyn_traits(reg_info.def_id);
303 nice_region_error::suggest_new_region_bound(
307 hidden_region.to_string(),
309 format!("captures `{}`", hidden_region),
311 Some(reg_info.def_id),
316 // Ugh. This is a painful case: the hidden region is not one
317 // that we can easily summarize or explain. This can happen
319 // `tests/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
322 // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
323 // if condition() { a } else { b }
327 // Here the captured lifetime is the intersection of `'a` and
328 // `'b`, which we can't quite express.
330 // We can at least report a really cryptic error for now.
331 note_and_explain_region(
334 &format!("hidden type `{}` captures ", hidden_ty),
345 impl<'tcx> InferCtxt<'tcx> {
346 pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Ty<'tcx>> {
347 let (def_id, substs) = match *ty.kind() {
348 ty::Alias(_, ty::AliasTy { def_id, substs, .. })
350 self.tcx.def_kind(def_id),
351 DefKind::OpaqueTy | DefKind::ImplTraitPlaceholder
359 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
360 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
362 self.tcx.bound_explicit_item_bounds(def_id).subst_iter_copied(self.tcx, substs).find_map(
366 .map_bound(|kind| match kind {
367 ty::PredicateKind::Clause(ty::Clause::Projection(projection_predicate))
368 if projection_predicate.projection_ty.def_id == item_def_id =>
370 projection_predicate.term.ty()
381 impl<'tcx> TypeErrCtxt<'_, 'tcx> {
382 pub fn report_region_errors(
384 generic_param_scope: LocalDefId,
385 errors: &[RegionResolutionError<'tcx>],
387 debug!("report_region_errors(): {} errors to start", errors.len());
389 // try to pre-process the errors, which will group some of them
390 // together into a `ProcessedErrors` group:
391 let errors = self.process_errors(errors);
393 debug!("report_region_errors: {} errors after preprocessing", errors.len());
395 for error in errors {
396 debug!("report_region_errors: error = {:?}", error);
398 if !self.try_report_nice_region_error(&error) {
399 match error.clone() {
400 // These errors could indicate all manner of different
401 // problems with many different solutions. Rather
402 // than generate a "one size fits all" error, what we
403 // attempt to do is go through a number of specific
404 // scenarios and try to find the best way to present
405 // the error. If all of these fails, we fall back to a rather
406 // general bit of code that displays the error information
407 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
408 if sub.is_placeholder() || sup.is_placeholder() {
409 self.report_placeholder_failure(origin, sub, sup).emit();
411 self.report_concrete_failure(origin, sub, sup).emit();
415 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
416 self.report_generic_bound_failure(
425 RegionResolutionError::SubSupConflict(
434 if sub_r.is_placeholder() {
435 self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
436 } else if sup_r.is_placeholder() {
437 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
439 self.report_sub_sup_conflict(
440 var_origin, sub_origin, sub_r, sup_origin, sup_r,
445 RegionResolutionError::UpperBoundUniverseConflict(
452 assert!(sup_r.is_placeholder());
454 // Make a dummy value for the "sub region" --
455 // this is the initial value of the
456 // placeholder. In practice, we expect more
457 // tailored errors that don't really use this
459 let sub_r = self.tcx.lifetimes.re_erased;
461 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
468 // This method goes through all the errors and try to group certain types
469 // of error together, for the purpose of suggesting explicit lifetime
470 // parameters to the user. This is done so that we can have a more
471 // complete view of what lifetimes should be the same.
472 // If the return value is an empty vector, it means that processing
473 // failed (so the return value of this method should not be used).
475 // The method also attempts to weed out messages that seem like
476 // duplicates that will be unhelpful to the end-user. But
477 // obviously it never weeds out ALL errors.
480 errors: &[RegionResolutionError<'tcx>],
481 ) -> Vec<RegionResolutionError<'tcx>> {
482 debug!("process_errors()");
484 // We want to avoid reporting generic-bound failures if we can
485 // avoid it: these have a very high rate of being unhelpful in
486 // practice. This is because they are basically secondary
487 // checks that test the state of the region graph after the
488 // rest of inference is done, and the other kinds of errors
489 // indicate that the region constraint graph is internally
490 // inconsistent, so these test results are likely to be
493 // Therefore, we filter them out of the list unless they are
494 // the only thing in the list.
496 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
497 RegionResolutionError::GenericBoundFailure(..) => true,
498 RegionResolutionError::ConcreteFailure(..)
499 | RegionResolutionError::SubSupConflict(..)
500 | RegionResolutionError::UpperBoundUniverseConflict(..) => false,
503 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
506 errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
509 // sort the errors by span, for better error message stability.
510 errors.sort_by_key(|u| match *u {
511 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
512 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
513 RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(),
514 RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
519 /// Adds a note if the types come from similarly named crates
520 fn check_and_note_conflicting_crates(&self, err: &mut Diagnostic, terr: TypeError<'tcx>) {
521 use hir::def_id::CrateNum;
522 use rustc_hir::definitions::DisambiguatedDefPathData;
523 use ty::print::Printer;
524 use ty::subst::GenericArg;
526 struct AbsolutePathPrinter<'tcx> {
530 struct NonTrivialPath;
532 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
533 type Error = NonTrivialPath;
535 type Path = Vec<String>;
538 type DynExistential = !;
541 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
545 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
549 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
553 fn print_dyn_existential(
555 _predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
556 ) -> Result<Self::DynExistential, Self::Error> {
560 fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
564 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
565 Ok(vec![self.tcx.crate_name(cnum).to_string()])
570 _trait_ref: Option<ty::TraitRef<'tcx>>,
571 ) -> Result<Self::Path, Self::Error> {
577 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
578 _disambiguated_data: &DisambiguatedDefPathData,
580 _trait_ref: Option<ty::TraitRef<'tcx>>,
581 ) -> Result<Self::Path, Self::Error> {
586 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
587 disambiguated_data: &DisambiguatedDefPathData,
588 ) -> Result<Self::Path, Self::Error> {
589 let mut path = print_prefix(self)?;
590 path.push(disambiguated_data.to_string());
593 fn path_generic_args(
595 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
596 _args: &[GenericArg<'tcx>],
597 ) -> Result<Self::Path, Self::Error> {
602 let report_path_match = |err: &mut Diagnostic, did1: DefId, did2: DefId| {
603 // Only external crates, if either is from a local
604 // module we could have false positives
605 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
607 |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
609 // We compare strings because DefPath can be different
610 // for imported and non-imported crates
611 let same_path = || -> Result<_, NonTrivialPath> {
612 Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
613 || abs_path(did1)? == abs_path(did2)?)
615 if same_path().unwrap_or(false) {
616 let crate_name = self.tcx.crate_name(did1.krate);
618 "perhaps two different versions of crate `{}` are being used?",
625 TypeError::Sorts(ref exp_found) => {
626 // if they are both "path types", there's a chance of ambiguity
627 // due to different versions of the same crate
628 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
629 (exp_found.expected.kind(), exp_found.found.kind())
631 report_path_match(err, exp_adt.did(), found_adt.did());
634 TypeError::Traits(ref exp_found) => {
635 report_path_match(err, exp_found.expected, exp_found.found);
637 _ => (), // FIXME(#22750) handle traits and stuff
641 fn note_error_origin(
643 err: &mut Diagnostic,
644 cause: &ObligationCause<'tcx>,
645 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
646 terr: TypeError<'tcx>,
648 match *cause.code() {
649 ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
650 let ty = self.resolve_vars_if_possible(root_ty);
651 if !matches!(ty.kind(), ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)))
653 // don't show type `_`
654 if span.desugaring_kind() == Some(DesugaringKind::ForLoop)
655 && let ty::Adt(def, substs) = ty.kind()
656 && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option)
658 err.span_label(span, format!("this is an iterator with items of type `{}`", substs.type_at(0)));
660 err.span_label(span, format!("this expression has type `{}`", ty));
663 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
664 && ty.is_box() && ty.boxed_ty() == found
665 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
669 "consider dereferencing the boxed value",
670 format!("*{}", snippet),
671 Applicability::MachineApplicable,
675 ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
676 err.span_label(span, "expected due to this");
678 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
688 opt_suggest_box_span,
692 hir::MatchSource::TryDesugar => {
693 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
694 let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
695 let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
696 let arg_expr = args.first().expect("try desugaring call w/out arg");
697 self.typeck_results.as_ref().and_then(|typeck_results| {
698 typeck_results.expr_ty_opt(arg_expr)
701 bug!("try desugaring w/out call expr as scrutinee");
705 Some(ty) if expected == ty => {
706 let source_map = self.tcx.sess.source_map();
708 source_map.end_point(cause.span),
709 "try removing this `?`",
711 Applicability::MachineApplicable,
719 // `prior_arm_ty` can be `!`, `expected` will have better info when present.
720 let t = self.resolve_vars_if_possible(match exp_found {
721 Some(ty::error::ExpectedFound { expected, .. }) => expected,
724 let source_map = self.tcx.sess.source_map();
725 let mut any_multiline_arm = source_map.is_multiline(arm_span);
726 if prior_arms.len() <= 4 {
727 for sp in prior_arms {
728 any_multiline_arm |= source_map.is_multiline(*sp);
729 err.span_label(*sp, format!("this is found to be of type `{}`", t));
731 } else if let Some(sp) = prior_arms.last() {
732 any_multiline_arm |= source_map.is_multiline(*sp);
735 format!("this and all prior arms are found to be of type `{}`", t),
738 let outer = if any_multiline_arm || !source_map.is_multiline(cause.span) {
739 // Cover just `match` and the scrutinee expression, not
740 // the entire match body, to reduce diagram noise.
741 cause.span.shrink_to_lo().to(scrut_span)
745 let msg = "`match` arms have incompatible types";
746 err.span_label(outer, msg);
747 self.suggest_remove_semi_or_return_binding(
756 if let Some(ret_sp) = opt_suggest_box_span {
757 // Get return type span and point to it.
758 self.suggest_boxing_for_return_impl_trait(
761 prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
766 ObligationCauseCode::IfExpression(box IfExpressionCause {
772 opt_suggest_box_span,
774 let then_span = self.find_block_span_from_hir_id(then_id);
775 let else_span = self.find_block_span_from_hir_id(else_id);
776 err.span_label(then_span, "expected because of this");
777 if let Some(sp) = outer_span {
778 err.span_label(sp, "`if` and `else` have incompatible types");
780 self.suggest_remove_semi_or_return_binding(
789 if let Some(ret_sp) = opt_suggest_box_span {
790 self.suggest_boxing_for_return_impl_trait(
793 [then_span, else_span].into_iter(),
797 ObligationCauseCode::LetElse => {
798 err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
799 err.help("...or use `match` instead of `let...else`");
802 if let ObligationCauseCode::BindingObligation(_, span)
803 | ObligationCauseCode::ExprBindingObligation(_, span, ..)
804 = cause.code().peel_derives()
805 && let TypeError::RegionsPlaceholderMismatch = terr
807 err.span_note( * span,
808 "the lifetime requirement is introduced here");
814 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
815 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
816 /// populate `other_value` with `other_ty`.
820 /// ^^^^--------^ this is highlighted
822 /// | this type argument is exactly the same as the other type, not highlighted
823 /// this is highlighted
825 /// -------- this type is the same as a type argument in the other type, not highlighted
829 value: &mut DiagnosticStyledString,
830 other_value: &mut DiagnosticStyledString,
832 sub: ty::subst::SubstsRef<'tcx>,
836 // `value` and `other_value` hold two incomplete type representation for display.
837 // `name` is the path of both types being compared. `sub`
838 value.push_highlighted(name);
841 value.push_highlighted("<");
844 // Output the lifetimes for the first type
848 let s = lifetime.to_string();
849 if s.is_empty() { "'_".to_string() } else { s }
853 if !lifetimes.is_empty() {
854 if sub.regions().count() < len {
855 value.push_normal(lifetimes + ", ");
857 value.push_normal(lifetimes);
861 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
862 // `pos` and `other_ty`.
863 for (i, type_arg) in sub.types().enumerate() {
865 let values = self.cmp(type_arg, other_ty);
866 value.0.extend((values.0).0);
867 other_value.0.extend((values.1).0);
869 value.push_highlighted(type_arg.to_string());
872 if len > 0 && i != len - 1 {
873 value.push_normal(", ");
877 value.push_highlighted(">");
881 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
882 /// as that is the difference to the other type.
884 /// For the following code:
886 /// ```ignore (illustrative)
887 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
890 /// The type error output will behave in the following way:
894 /// ^^^^--------^ this is highlighted
896 /// | this type argument is exactly the same as the other type, not highlighted
897 /// this is highlighted
899 /// -------- this type is the same as a type argument in the other type, not highlighted
903 mut t1_out: &mut DiagnosticStyledString,
904 mut t2_out: &mut DiagnosticStyledString,
906 sub: &'tcx [ty::GenericArg<'tcx>],
910 // FIXME/HACK: Go back to `SubstsRef` to use its inherent methods,
911 // ideally that shouldn't be necessary.
912 let sub = self.tcx.intern_substs(sub);
913 for (i, ta) in sub.types().enumerate() {
915 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
918 if let ty::Adt(def, _) = ta.kind() {
919 let path_ = self.tcx.def_path_str(def.did());
920 if path_ == other_path {
921 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
929 /// Adds a `,` to the type representation only if it is appropriate.
932 value: &mut DiagnosticStyledString,
933 other_value: &mut DiagnosticStyledString,
937 if len > 0 && pos != len - 1 {
938 value.push_normal(", ");
939 other_value.push_normal(", ");
943 /// Given two `fn` signatures highlight only sub-parts that are different.
946 sig1: &ty::PolyFnSig<'tcx>,
947 sig2: &ty::PolyFnSig<'tcx>,
948 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
949 let sig1 = &(self.normalize_fn_sig)(*sig1);
950 let sig2 = &(self.normalize_fn_sig)(*sig2);
952 let get_lifetimes = |sig| {
953 use rustc_hir::def::Namespace;
954 let (_, sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
955 .name_all_regions(sig)
957 let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
958 (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
961 let (lt1, sig1) = get_lifetimes(sig1);
962 let (lt2, sig2) = get_lifetimes(sig2);
964 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
966 DiagnosticStyledString::normal("".to_string()),
967 DiagnosticStyledString::normal("".to_string()),
970 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
972 values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
973 values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
975 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
977 if sig1.abi != abi::Abi::Rust {
978 values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
980 if sig2.abi != abi::Abi::Rust {
981 values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
984 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
986 let lifetime_diff = lt1 != lt2;
987 values.0.push(lt1, lifetime_diff);
988 values.1.push(lt2, lifetime_diff);
990 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
992 values.0.push_normal("fn(");
993 values.1.push_normal("fn(");
995 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
997 let len1 = sig1.inputs().len();
998 let len2 = sig2.inputs().len();
1000 for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
1001 let (x1, x2) = self.cmp(*l, *r);
1002 (values.0).0.extend(x1.0);
1003 (values.1).0.extend(x2.0);
1004 self.push_comma(&mut values.0, &mut values.1, len1, i);
1007 for (i, l) in sig1.inputs().iter().enumerate() {
1008 values.0.push_highlighted(l.to_string());
1010 values.0.push_highlighted(", ");
1013 for (i, r) in sig2.inputs().iter().enumerate() {
1014 values.1.push_highlighted(r.to_string());
1016 values.1.push_highlighted(", ");
1021 if sig1.c_variadic {
1023 values.0.push_normal(", ");
1025 values.0.push("...", !sig2.c_variadic);
1027 if sig2.c_variadic {
1029 values.1.push_normal(", ");
1031 values.1.push("...", !sig1.c_variadic);
1034 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1036 values.0.push_normal(")");
1037 values.1.push_normal(")");
1039 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1041 let output1 = sig1.output();
1042 let output2 = sig2.output();
1043 let (x1, x2) = self.cmp(output1, output2);
1044 if !output1.is_unit() {
1045 values.0.push_normal(" -> ");
1046 (values.0).0.extend(x1.0);
1048 if !output2.is_unit() {
1049 values.1.push_normal(" -> ");
1050 (values.1).0.extend(x2.0);
1055 /// Compares two given types, eliding parts that are the same between them and highlighting
1056 /// relevant differences, and return two representation of those types for highlighted printing.
1061 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
1062 debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1065 fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1066 match (a.kind(), b.kind()) {
1067 (a, b) if *a == *b => true,
1068 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1070 &ty::Infer(ty::InferTy::IntVar(_)),
1071 &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1073 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1075 &ty::Infer(ty::InferTy::FloatVar(_)),
1076 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1082 fn push_ty_ref<'tcx>(
1083 region: ty::Region<'tcx>,
1085 mutbl: hir::Mutability,
1086 s: &mut DiagnosticStyledString,
1088 let mut r = region.to_string();
1094 s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1095 s.push_normal(ty.to_string());
1098 // process starts here
1099 match (t1.kind(), t2.kind()) {
1100 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1101 let did1 = def1.did();
1102 let did2 = def2.did();
1103 let sub_no_defaults_1 =
1104 self.tcx.generics_of(did1).own_substs_no_defaults(self.tcx, sub1);
1105 let sub_no_defaults_2 =
1106 self.tcx.generics_of(did2).own_substs_no_defaults(self.tcx, sub2);
1107 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1108 let path1 = self.tcx.def_path_str(did1);
1109 let path2 = self.tcx.def_path_str(did2);
1111 // Easy case. Replace same types with `_` to shorten the output and highlight
1112 // the differing ones.
1113 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1116 // --- ^ type argument elided
1118 // highlighted in output
1119 values.0.push_normal(path1);
1120 values.1.push_normal(path2);
1122 // Avoid printing out default generic parameters that are common to both
1124 let len1 = sub_no_defaults_1.len();
1125 let len2 = sub_no_defaults_2.len();
1126 let common_len = cmp::min(len1, len2);
1127 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1128 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1129 let common_default_params =
1130 iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1131 .filter(|(a, b)| a == b)
1133 let len = sub1.len() - common_default_params;
1134 let consts_offset = len - sub1.consts().count();
1136 // Only draw `<...>` if there are lifetime/type arguments.
1138 values.0.push_normal("<");
1139 values.1.push_normal("<");
1142 fn lifetime_display(lifetime: Region<'_>) -> String {
1143 let s = lifetime.to_string();
1144 if s.is_empty() { "'_".to_string() } else { s }
1146 // At one point we'd like to elide all lifetimes here, they are irrelevant for
1147 // all diagnostics that use this output
1151 // ^^ ^^ --- type arguments are not elided
1153 // | elided as they were the same
1154 // not elided, they were different, but irrelevant
1156 // For bound lifetimes, keep the names of the lifetimes,
1157 // even if they are the same so that it's clear what's happening
1158 // if we have something like
1160 // for<'r, 's> fn(Inv<'r>, Inv<'s>)
1161 // for<'r> fn(Inv<'r>, Inv<'r>)
1162 let lifetimes = sub1.regions().zip(sub2.regions());
1163 for (i, lifetimes) in lifetimes.enumerate() {
1164 let l1 = lifetime_display(lifetimes.0);
1165 let l2 = lifetime_display(lifetimes.1);
1166 if lifetimes.0 != lifetimes.1 {
1167 values.0.push_highlighted(l1);
1168 values.1.push_highlighted(l2);
1169 } else if lifetimes.0.is_late_bound() {
1170 values.0.push_normal(l1);
1171 values.1.push_normal(l2);
1173 values.0.push_normal("'_");
1174 values.1.push_normal("'_");
1176 self.push_comma(&mut values.0, &mut values.1, len, i);
1179 // We're comparing two types with the same path, so we compare the type
1180 // arguments for both. If they are the same, do not highlight and elide from the
1184 // ^ elided type as this type argument was the same in both sides
1185 let type_arguments = sub1.types().zip(sub2.types());
1186 let regions_len = sub1.regions().count();
1187 let num_display_types = consts_offset - regions_len;
1188 for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1189 let i = i + regions_len;
1190 if ta1 == ta2 && !self.tcx.sess.verbose() {
1191 values.0.push_normal("_");
1192 values.1.push_normal("_");
1194 let (x1, x2) = self.cmp(ta1, ta2);
1195 (values.0).0.extend(x1.0);
1196 (values.1).0.extend(x2.0);
1198 self.push_comma(&mut values.0, &mut values.1, len, i);
1201 // Do the same for const arguments, if they are equal, do not highlight and
1202 // elide them from the output.
1203 let const_arguments = sub1.consts().zip(sub2.consts());
1204 for (i, (ca1, ca2)) in const_arguments.enumerate() {
1205 let i = i + consts_offset;
1206 if ca1 == ca2 && !self.tcx.sess.verbose() {
1207 values.0.push_normal("_");
1208 values.1.push_normal("_");
1210 values.0.push_highlighted(ca1.to_string());
1211 values.1.push_highlighted(ca2.to_string());
1213 self.push_comma(&mut values.0, &mut values.1, len, i);
1216 // Close the type argument bracket.
1217 // Only draw `<...>` if there are lifetime/type arguments.
1219 values.0.push_normal(">");
1220 values.1.push_normal(">");
1225 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1227 // ------- this type argument is exactly the same as the other type
1243 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1246 // ------- this type argument is exactly the same as the other type
1261 // We can't find anything in common, highlight relevant part of type path.
1262 // let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1263 // foo::bar::Baz<Qux>
1264 // foo::bar::Bar<Zar>
1265 // -------- this part of the path is different
1267 let t1_str = t1.to_string();
1268 let t2_str = t2.to_string();
1269 let min_len = t1_str.len().min(t2_str.len());
1271 const SEPARATOR: &str = "::";
1272 let separator_len = SEPARATOR.len();
1273 let split_idx: usize =
1274 iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1275 .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1276 .map(|(mod_str, _)| mod_str.len() + separator_len)
1279 debug!(?separator_len, ?split_idx, ?min_len, "cmp");
1281 if split_idx >= min_len {
1282 // paths are identical, highlight everything
1284 DiagnosticStyledString::highlighted(t1_str),
1285 DiagnosticStyledString::highlighted(t2_str),
1288 let (common, uniq1) = t1_str.split_at(split_idx);
1289 let (_, uniq2) = t2_str.split_at(split_idx);
1290 debug!(?common, ?uniq1, ?uniq2, "cmp");
1292 values.0.push_normal(common);
1293 values.0.push_highlighted(uniq1);
1294 values.1.push_normal(common);
1295 values.1.push_highlighted(uniq2);
1302 // When finding T != &T, highlight only the borrow
1303 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(ref_ty1, t2) => {
1304 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1305 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1306 values.1.push_normal(t2.to_string());
1309 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(t1, ref_ty2) => {
1310 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1311 values.0.push_normal(t1.to_string());
1312 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1316 // When encountering &T != &mut T, highlight only the borrow
1317 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1318 if equals(ref_ty1, ref_ty2) =>
1320 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1321 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1322 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1326 // When encountering tuples of the same size, highlight only the differing types
1327 (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1329 (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1330 let len = substs1.len();
1331 for (i, (left, right)) in substs1.iter().zip(substs2).enumerate() {
1332 let (x1, x2) = self.cmp(left, right);
1333 (values.0).0.extend(x1.0);
1334 (values.1).0.extend(x2.0);
1335 self.push_comma(&mut values.0, &mut values.1, len, i);
1338 // Keep the output for single element tuples as `(ty,)`.
1339 values.0.push_normal(",");
1340 values.1.push_normal(",");
1342 values.0.push_normal(")");
1343 values.1.push_normal(")");
1347 (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1348 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1349 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1350 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1351 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1352 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1353 let same_path = path1 == path2;
1354 values.0.push(path1, !same_path);
1355 values.1.push(path2, !same_path);
1359 (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1360 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1361 let mut values = self.cmp_fn_sig(&sig1, sig2);
1362 values.0.push_highlighted(format!(
1364 self.tcx.def_path_str_with_substs(*did1, substs1)
1369 (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1370 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1371 let mut values = self.cmp_fn_sig(sig1, &sig2);
1372 values.1.push_normal(format!(
1374 self.tcx.def_path_str_with_substs(*did2, substs2)
1379 (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1382 if t1 == t2 && !self.tcx.sess.verbose() {
1383 // The two types are the same, elide and don't highlight.
1384 (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1386 // We couldn't find anything in common, highlight everything.
1388 DiagnosticStyledString::highlighted(t1.to_string()),
1389 DiagnosticStyledString::highlighted(t2.to_string()),
1396 /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
1397 /// the return type of `async fn`s.
1399 /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1401 /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
1402 /// the message in `secondary_span` as the primary label, and apply the message that would
1403 /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
1404 /// E0271, like `tests/ui/issues/issue-39970.stderr`.
1407 skip(self, diag, secondary_span, swap_secondary_and_primary, prefer_label)
1409 pub fn note_type_err(
1411 diag: &mut Diagnostic,
1412 cause: &ObligationCause<'tcx>,
1413 secondary_span: Option<(Span, String)>,
1414 mut values: Option<ValuePairs<'tcx>>,
1415 terr: TypeError<'tcx>,
1416 swap_secondary_and_primary: bool,
1419 let span = cause.span();
1421 // For some types of errors, expected-found does not make
1422 // sense, so just ignore the values we were given.
1423 if let TypeError::CyclicTy(_) = terr {
1426 struct OpaqueTypesVisitor<'tcx> {
1427 types: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1428 expected: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1429 found: FxIndexMap<TyCategory, FxIndexSet<Span>>,
1434 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1435 fn visit_expected_found(
1437 expected: impl TypeVisitable<'tcx>,
1438 found: impl TypeVisitable<'tcx>,
1441 let mut types_visitor = OpaqueTypesVisitor {
1442 types: Default::default(),
1443 expected: Default::default(),
1444 found: Default::default(),
1448 // The visitor puts all the relevant encountered types in `self.types`, but in
1449 // here we want to visit two separate types with no relation to each other, so we
1450 // move the results from `types` to `expected` or `found` as appropriate.
1451 expected.visit_with(&mut types_visitor);
1452 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1453 found.visit_with(&mut types_visitor);
1454 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1458 fn report(&self, err: &mut Diagnostic) {
1459 self.add_labels_for_types(err, "expected", &self.expected);
1460 self.add_labels_for_types(err, "found", &self.found);
1463 fn add_labels_for_types(
1465 err: &mut Diagnostic,
1467 types: &FxIndexMap<TyCategory, FxIndexSet<Span>>,
1469 for (key, values) in types.iter() {
1470 let count = values.len();
1471 let kind = key.descr();
1472 let mut returned_async_output_error = false;
1474 if sp.is_desugaring(DesugaringKind::Async) && !returned_async_output_error {
1475 if [sp] != err.span.primary_spans() {
1476 let mut span: MultiSpan = sp.into();
1477 span.push_span_label(
1480 "checked the `Output` of this `async fn`, {}{} {}{}",
1481 if count > 1 { "one of the " } else { "" },
1489 "while checking the return type of the `async fn`",
1495 "checked the `Output` of this `async fn`, {}{} {}{}",
1496 if count > 1 { "one of the " } else { "" },
1502 err.note("while checking the return type of the `async fn`");
1504 returned_async_output_error = true;
1510 if count == 1 { "the " } else { "one of the " },
1522 impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1523 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1524 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1525 let span = self.tcx.def_span(def_id);
1526 // Avoid cluttering the output when the "found" and error span overlap:
1528 // error[E0308]: mismatched types
1529 // --> $DIR/issue-20862.rs:2:5
1534 // | the found closure
1535 // | expected `()`, found closure
1537 // = note: expected unit type `()`
1538 // found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1539 if !self.ignore_span.overlaps(span) {
1540 self.types.entry(kind).or_default().insert(span);
1543 t.super_visit_with(self)
1547 debug!("note_type_err(diag={:?})", diag);
1549 Variable(ty::error::ExpectedFound<Ty<'a>>),
1550 Fixed(&'static str),
1552 let (expected_found, exp_found, is_simple_error, values) = match values {
1553 None => (None, Mismatch::Fixed("type"), false, None),
1555 let values = self.resolve_vars_if_possible(values);
1556 let (is_simple_error, exp_found) = match values {
1557 ValuePairs::Terms(infer::ExpectedFound { expected, found }) => {
1558 match (expected.unpack(), found.unpack()) {
1559 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
1561 expected.is_simple_text() && found.is_simple_text();
1562 OpaqueTypesVisitor::visit_expected_found(
1563 self.tcx, expected, found, span,
1569 Mismatch::Variable(infer::ExpectedFound { expected, found }),
1572 (ty::TermKind::Const(_), ty::TermKind::Const(_)) => {
1573 (false, Mismatch::Fixed("constant"))
1575 _ => (false, Mismatch::Fixed("type")),
1578 ValuePairs::Sigs(infer::ExpectedFound { expected, found }) => {
1579 OpaqueTypesVisitor::visit_expected_found(self.tcx, expected, found, span)
1581 (false, Mismatch::Fixed("signature"))
1583 ValuePairs::TraitRefs(_) | ValuePairs::PolyTraitRefs(_) => {
1584 (false, Mismatch::Fixed("trait"))
1586 ValuePairs::Regions(_) => (false, Mismatch::Fixed("lifetime")),
1588 let Some(vals) = self.values_str(values) else {
1589 // Derived error. Cancel the emitter.
1590 // NOTE(eddyb) this was `.cancel()`, but `diag`
1591 // is borrowed, so we can't fully defuse it.
1592 diag.downgrade_to_delayed_bug();
1595 (Some(vals), exp_found, is_simple_error, Some(values))
1599 let mut label_or_note = |span: Span, msg: &str| {
1600 if (prefer_label && is_simple_error) || &[span] == diag.span.primary_spans() {
1601 diag.span_label(span, msg);
1603 diag.span_note(span, msg);
1606 if let Some((sp, msg)) = secondary_span {
1607 if swap_secondary_and_primary {
1608 let terr = if let Some(infer::ValuePairs::Terms(infer::ExpectedFound {
1613 format!("expected this to be `{}`", expected)
1617 label_or_note(sp, &terr);
1618 label_or_note(span, &msg);
1620 label_or_note(span, &terr.to_string());
1621 label_or_note(sp, &msg);
1624 label_or_note(span, &terr.to_string());
1627 if let Some((expected, found, exp_p, found_p)) = expected_found {
1628 let (expected_label, found_label, exp_found) = match exp_found {
1629 Mismatch::Variable(ef) => (
1630 ef.expected.prefix_string(self.tcx),
1631 ef.found.prefix_string(self.tcx),
1634 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1637 enum Similar<'tcx> {
1638 Adts { expected: ty::AdtDef<'tcx>, found: ty::AdtDef<'tcx> },
1639 PrimitiveFound { expected: ty::AdtDef<'tcx>, found: Ty<'tcx> },
1640 PrimitiveExpected { expected: Ty<'tcx>, found: ty::AdtDef<'tcx> },
1643 let similarity = |ExpectedFound { expected, found }: ExpectedFound<Ty<'tcx>>| {
1644 if let ty::Adt(expected, _) = expected.kind() && let Some(primitive) = found.primitive_symbol() {
1645 let path = self.tcx.def_path(expected.did()).data;
1646 let name = path.last().unwrap().data.get_opt_name();
1647 if name == Some(primitive) {
1648 return Some(Similar::PrimitiveFound { expected: *expected, found });
1650 } else if let Some(primitive) = expected.primitive_symbol() && let ty::Adt(found, _) = found.kind() {
1651 let path = self.tcx.def_path(found.did()).data;
1652 let name = path.last().unwrap().data.get_opt_name();
1653 if name == Some(primitive) {
1654 return Some(Similar::PrimitiveExpected { expected, found: *found });
1656 } else if let ty::Adt(expected, _) = expected.kind() && let ty::Adt(found, _) = found.kind() {
1657 if !expected.did().is_local() && expected.did().krate == found.did().krate {
1658 // Most likely types from different versions of the same crate
1659 // are in play, in which case this message isn't so helpful.
1660 // A "perhaps two different versions..." error is already emitted for that.
1663 let f_path = self.tcx.def_path(found.did()).data;
1664 let e_path = self.tcx.def_path(expected.did()).data;
1666 if let (Some(e_last), Some(f_last)) = (e_path.last(), f_path.last()) && e_last == f_last {
1667 return Some(Similar::Adts{expected: *expected, found: *found});
1674 // If two types mismatch but have similar names, mention that specifically.
1675 TypeError::Sorts(values) if let Some(s) = similarity(values) => {
1676 let diagnose_primitive =
1680 diagnostic: &mut Diagnostic| {
1681 let name = shadow.sort_string(self.tcx);
1682 diagnostic.note(format!(
1683 "{prim} and {name} have similar names, but are actually distinct types"
1686 .note(format!("{prim} is a primitive defined by the language"));
1687 let def_span = self.tcx.def_span(defid);
1688 let msg = if defid.is_local() {
1689 format!("{name} is defined in the current crate")
1691 let crate_name = self.tcx.crate_name(defid.krate);
1692 format!("{name} is defined in crate `{crate_name}")
1694 diagnostic.span_note(def_span, msg);
1698 |expected_adt : ty::AdtDef<'tcx>,
1699 found_adt: ty::AdtDef<'tcx>,
1700 diagnostic: &mut Diagnostic| {
1701 let found_name = values.found.sort_string(self.tcx);
1702 let expected_name = values.expected.sort_string(self.tcx);
1704 let found_defid = found_adt.did();
1705 let expected_defid = expected_adt.did();
1707 diagnostic.note(format!("{found_name} and {expected_name} have similar names, but are actually distinct types"));
1708 for (defid, name) in
1709 [(found_defid, found_name), (expected_defid, expected_name)]
1711 let def_span = self.tcx.def_span(defid);
1713 let msg = if found_defid.is_local() && expected_defid.is_local() {
1716 .parent_module_from_def_id(defid.expect_local())
1718 let module_name = self.tcx.def_path(module).to_string_no_crate_verbose();
1719 format!("{name} is defined in module `crate{module_name}` of the current crate")
1720 } else if defid.is_local() {
1721 format!("{name} is defined in the current crate")
1723 let crate_name = self.tcx.crate_name(defid.krate);
1724 format!("{name} is defined in crate `{crate_name}`")
1726 diagnostic.span_note(def_span, msg);
1731 Similar::Adts{expected, found} => {
1732 diagnose_adts(expected, found, diag)
1734 Similar::PrimitiveFound{expected, found: prim} => {
1735 diagnose_primitive(prim, values.expected, expected.did(), diag)
1737 Similar::PrimitiveExpected{expected: prim, found} => {
1738 diagnose_primitive(prim, values.found, found.did(), diag)
1742 TypeError::Sorts(values) => {
1743 let extra = expected == found;
1744 let sort_string = |ty: Ty<'tcx>, path: Option<PathBuf>| {
1745 let mut s = match (extra, ty.kind()) {
1746 (true, ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. })) => {
1747 let sm = self.tcx.sess.source_map();
1748 let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1750 " (opaque type at <{}:{}:{}>)",
1751 sm.filename_for_diagnostics(&pos.file.name),
1753 pos.col.to_usize() + 1,
1756 (true, ty::Alias(ty::Projection, proj))
1757 if self.tcx.def_kind(proj.def_id)
1758 == DefKind::ImplTraitPlaceholder =>
1760 let sm = self.tcx.sess.source_map();
1761 let pos = sm.lookup_char_pos(self.tcx.def_span(proj.def_id).lo());
1763 " (trait associated opaque type at <{}:{}:{}>)",
1764 sm.filename_for_diagnostics(&pos.file.name),
1766 pos.col.to_usize() + 1,
1769 (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1770 (false, _) => "".to_string(),
1772 if let Some(path) = path {
1773 s.push_str(&format!(
1774 "\nthe full type name has been written to '{}'",
1780 if !(values.expected.is_simple_text() && values.found.is_simple_text())
1781 || (exp_found.map_or(false, |ef| {
1782 // This happens when the type error is a subset of the expectation,
1783 // like when you have two references but one is `usize` and the other
1784 // is `f32`. In those cases we still want to show the `note`. If the
1785 // value from `ef` is `Infer(_)`, then we ignore it.
1786 if !ef.expected.is_ty_or_numeric_infer() {
1787 ef.expected != values.expected
1788 } else if !ef.found.is_ty_or_numeric_infer() {
1789 ef.found != values.found
1795 diag.note_expected_found_extra(
1800 &sort_string(values.expected, exp_p),
1801 &sort_string(values.found, found_p),
1807 "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1808 exp_found, expected, found
1810 if !is_simple_error || terr.must_include_note() {
1811 diag.note_expected_found(&expected_label, expected, &found_label, found);
1816 let exp_found = match exp_found {
1817 Mismatch::Variable(exp_found) => Some(exp_found),
1818 Mismatch::Fixed(_) => None,
1820 let exp_found = match terr {
1821 // `terr` has more accurate type information than `exp_found` in match expressions.
1822 ty::error::TypeError::Sorts(terr)
1823 if exp_found.map_or(false, |ef| terr.found == ef.found) =>
1829 debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
1830 if let Some(exp_found) = exp_found {
1831 let should_suggest_fixes =
1832 if let ObligationCauseCode::Pattern { root_ty, .. } = cause.code() {
1833 // Skip if the root_ty of the pattern is not the same as the expected_ty.
1834 // If these types aren't equal then we've probably peeled off a layer of arrays.
1835 self.same_type_modulo_infer(*root_ty, exp_found.expected)
1840 if should_suggest_fixes {
1841 self.suggest_tuple_pattern(cause, &exp_found, diag);
1842 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1843 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1844 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1845 self.suggest_function_pointers(cause, span, &exp_found, diag);
1849 self.check_and_note_conflicting_crates(diag, terr);
1851 self.note_and_explain_type_err(diag, terr, cause, span, cause.body_id.to_def_id());
1853 if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values
1854 && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind()
1855 && let Some(def_id) = def_id.as_local()
1856 && terr.involves_regions()
1858 let span = self.tcx.def_span(def_id);
1859 diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1862 // It reads better to have the error origin as the final
1864 self.note_error_origin(diag, cause, exp_found, terr);
1869 pub fn report_and_explain_type_error(
1871 trace: TypeTrace<'tcx>,
1872 terr: TypeError<'tcx>,
1873 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
1874 use crate::traits::ObligationCauseCode::MatchExpressionArm;
1876 debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
1878 let span = trace.cause.span();
1879 let failure_code = trace.cause.as_failure_code(terr);
1880 let mut diag = match failure_code {
1881 FailureCode::Error0038(did) => {
1882 let violations = self.tcx.object_safety_violations(did);
1883 report_object_safety_error(self.tcx, span, did, violations)
1885 FailureCode::Error0317(failure_str) => {
1886 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1888 FailureCode::Error0580(failure_str) => {
1889 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1891 FailureCode::Error0308(failure_str) => {
1892 fn escape_literal(s: &str) -> String {
1893 let mut escaped = String::with_capacity(s.len());
1894 let mut chrs = s.chars().peekable();
1895 while let Some(first) = chrs.next() {
1896 match (first, chrs.peek()) {
1897 ('\\', Some(&delim @ '"') | Some(&delim @ '\'')) => {
1899 escaped.push(delim);
1902 ('"' | '\'', _) => {
1906 (c, _) => escaped.push(c),
1911 let mut err = struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str);
1912 if let Some((expected, found)) = trace.values.ty() {
1913 match (expected.kind(), found.kind()) {
1914 (ty::Tuple(_), ty::Tuple(_)) => {}
1915 // If a tuple of length one was expected and the found expression has
1916 // parentheses around it, perhaps the user meant to write `(expr,)` to
1917 // build a tuple (issue #86100)
1918 (ty::Tuple(fields), _) => {
1919 self.emit_tuple_wrap_err(&mut err, span, found, fields)
1921 // If a byte was expected and the found expression is a char literal
1922 // containing a single ASCII character, perhaps the user meant to write `b'c'` to
1923 // specify a byte literal
1924 (ty::Uint(ty::UintTy::U8), ty::Char) => {
1925 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
1926 && let Some(code) = code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
1927 && code.chars().next().map_or(false, |c| c.is_ascii())
1929 err.span_suggestion(
1931 "if you meant to write a byte literal, prefix with `b`",
1932 format!("b'{}'", escape_literal(code)),
1933 Applicability::MachineApplicable,
1937 // If a character was expected and the found expression is a string literal
1938 // containing a single character, perhaps the user meant to write `'c'` to
1939 // specify a character literal (issue #92479)
1940 (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
1941 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
1942 && let Some(code) = code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
1943 && code.chars().count() == 1
1945 err.span_suggestion(
1947 "if you meant to write a `char` literal, use single quotes",
1948 format!("'{}'", escape_literal(code)),
1949 Applicability::MachineApplicable,
1953 // If a string was expected and the found expression is a character literal,
1954 // perhaps the user meant to write `"s"` to specify a string literal.
1955 (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
1956 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
1958 code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
1960 err.span_suggestion(
1962 "if you meant to write a `str` literal, use double quotes",
1963 format!("\"{}\"", escape_literal(code)),
1964 Applicability::MachineApplicable,
1969 // For code `if Some(..) = expr `, the type mismatch may be expected `bool` but found `()`,
1970 // we try to suggest to add the missing `let` for `if let Some(..) = expr`
1971 (ty::Bool, ty::Tuple(list)) => if list.len() == 0 {
1972 self.suggest_let_for_letchains(&mut err, &trace.cause, span);
1977 let code = trace.cause.code();
1978 if let &MatchExpressionArm(box MatchExpressionArmCause { source, .. }) = code
1979 && let hir::MatchSource::TryDesugar = source
1980 && let Some((expected_ty, found_ty, _, _)) = self.values_str(trace.values)
1983 "`?` operator cannot convert from `{}` to `{}`",
1985 expected_ty.content(),
1990 FailureCode::Error0644(failure_str) => {
1991 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1994 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false, false);
1998 fn emit_tuple_wrap_err(
2000 err: &mut Diagnostic,
2003 expected_fields: &List<Ty<'tcx>>,
2005 let [expected_tup_elem] = expected_fields[..] else { return };
2007 if !self.same_type_modulo_infer(expected_tup_elem, found) {
2011 let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2014 let msg = "use a trailing comma to create a tuple with one element";
2015 if code.starts_with('(') && code.ends_with(')') {
2016 let before_close = span.hi() - BytePos::from_u32(1);
2017 err.span_suggestion(
2018 span.with_hi(before_close).shrink_to_hi(),
2021 Applicability::MachineApplicable,
2024 err.multipart_suggestion(
2026 vec![(span.shrink_to_lo(), "(".into()), (span.shrink_to_hi(), ",)".into())],
2027 Applicability::MachineApplicable,
2034 values: ValuePairs<'tcx>,
2035 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString, Option<PathBuf>, Option<PathBuf>)>
2038 infer::Regions(exp_found) => self.expected_found_str(exp_found),
2039 infer::Terms(exp_found) => self.expected_found_str_term(exp_found),
2040 infer::TraitRefs(exp_found) => {
2041 let pretty_exp_found = ty::error::ExpectedFound {
2042 expected: exp_found.expected.print_only_trait_path(),
2043 found: exp_found.found.print_only_trait_path(),
2045 match self.expected_found_str(pretty_exp_found) {
2046 Some((expected, found, _, _)) if expected == found => {
2047 self.expected_found_str(exp_found)
2052 infer::PolyTraitRefs(exp_found) => {
2053 let pretty_exp_found = ty::error::ExpectedFound {
2054 expected: exp_found.expected.print_only_trait_path(),
2055 found: exp_found.found.print_only_trait_path(),
2057 match self.expected_found_str(pretty_exp_found) {
2058 Some((expected, found, _, _)) if expected == found => {
2059 self.expected_found_str(exp_found)
2064 infer::Sigs(exp_found) => {
2065 let exp_found = self.resolve_vars_if_possible(exp_found);
2066 if exp_found.references_error() {
2069 let (exp, fnd) = self.cmp_fn_sig(
2070 &ty::Binder::dummy(exp_found.expected),
2071 &ty::Binder::dummy(exp_found.found),
2073 Some((exp, fnd, None, None))
2078 fn expected_found_str_term(
2080 exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2081 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString, Option<PathBuf>, Option<PathBuf>)>
2083 let exp_found = self.resolve_vars_if_possible(exp_found);
2084 if exp_found.references_error() {
2088 Some(match (exp_found.expected.unpack(), exp_found.found.unpack()) {
2089 (ty::TermKind::Ty(expected), ty::TermKind::Ty(found)) => {
2090 let (mut exp, mut fnd) = self.cmp(expected, found);
2091 // Use the terminal width as the basis to determine when to compress the printed
2092 // out type, but give ourselves some leeway to avoid ending up creating a file for
2093 // a type that is somewhat shorter than the path we'd write to.
2094 let len = self.tcx.sess().diagnostic_width() + 40;
2095 let exp_s = exp.content();
2096 let fnd_s = fnd.content();
2097 let mut exp_p = None;
2098 let mut fnd_p = None;
2099 if exp_s.len() > len {
2100 let (exp_s, exp_path) = self.tcx.short_ty_string(expected);
2101 exp = DiagnosticStyledString::highlighted(exp_s);
2104 if fnd_s.len() > len {
2105 let (fnd_s, fnd_path) = self.tcx.short_ty_string(found);
2106 fnd = DiagnosticStyledString::highlighted(fnd_s);
2109 (exp, fnd, exp_p, fnd_p)
2112 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2113 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2120 /// Returns a string of the form "expected `{}`, found `{}`".
2121 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
2123 exp_found: ty::error::ExpectedFound<T>,
2124 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString, Option<PathBuf>, Option<PathBuf>)>
2126 let exp_found = self.resolve_vars_if_possible(exp_found);
2127 if exp_found.references_error() {
2132 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2133 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2139 pub fn report_generic_bound_failure(
2141 generic_param_scope: LocalDefId,
2143 origin: Option<SubregionOrigin<'tcx>>,
2144 bound_kind: GenericKind<'tcx>,
2147 self.construct_generic_bound_failure(generic_param_scope, span, origin, bound_kind, sub)
2151 pub fn construct_generic_bound_failure(
2153 generic_param_scope: LocalDefId,
2155 origin: Option<SubregionOrigin<'tcx>>,
2156 bound_kind: GenericKind<'tcx>,
2158 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2159 // Attempt to obtain the span of the parameter so we can
2160 // suggest adding an explicit lifetime bound to it.
2161 let generics = self.tcx.generics_of(generic_param_scope);
2162 // type_param_span is (span, has_bounds)
2163 let mut is_synthetic = false;
2164 let mut ast_generics = None;
2165 let type_param_span = match bound_kind {
2166 GenericKind::Param(ref param) => {
2167 // Account for the case where `param` corresponds to `Self`,
2168 // which doesn't have the expected type argument.
2169 if !(generics.has_self && param.index == 0) {
2170 let type_param = generics.type_param(param, self.tcx);
2171 is_synthetic = type_param.kind.is_synthetic();
2172 type_param.def_id.as_local().map(|def_id| {
2173 // Get the `hir::Param` to verify whether it already has any bounds.
2174 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
2175 // instead we suggest `T: 'a + 'b` in that case.
2176 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2177 ast_generics = self.tcx.hir().get_generics(hir_id.owner.def_id);
2179 ast_generics.and_then(|g| g.bounds_span_for_suggestions(def_id));
2180 // `sp` only covers `T`, change it so that it covers
2181 // `T:` when appropriate
2182 if let Some(span) = bounds {
2185 let sp = self.tcx.def_span(def_id);
2186 (sp.shrink_to_hi(), false)
2197 let mut possible = (b'a'..=b'z').map(|c| format!("'{}", c as char));
2199 iter::successors(Some(generics), |g| g.parent.map(|p| self.tcx.generics_of(p)))
2200 .flat_map(|g| &g.params)
2201 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2202 .map(|p| p.name.as_str())
2203 .collect::<Vec<_>>();
2205 .find(|candidate| !lts_names.contains(&&candidate[..]))
2206 .unwrap_or("'lt".to_string())
2209 let mut add_lt_suggs: Vec<Option<_>> = vec![];
2211 if let Some(ast_generics) = ast_generics {
2212 let named_lifetime_param_exist = ast_generics.params.iter().any(|p| {
2215 hir::GenericParamKind::Lifetime { kind: hir::LifetimeParamKind::Explicit }
2218 if named_lifetime_param_exist && let [param, ..] = ast_generics.params
2220 add_lt_suggs.push(Some((
2221 self.tcx.def_span(param.def_id).shrink_to_lo(),
2222 format!("{new_lt}, "),
2226 .push(Some((ast_generics.span.shrink_to_hi(), format!("<{new_lt}>"))));
2230 if let [param, ..] = &generics.params[..] && let Some(def_id) = param.def_id.as_local()
2233 .push(Some((self.tcx.def_span(def_id).shrink_to_lo(), format!("{new_lt}, "))));
2237 if let Some(ast_generics) = ast_generics {
2238 for p in ast_generics.params {
2239 if p.is_elided_lifetime() {
2244 .span_to_prev_source(p.span.shrink_to_hi())
2246 .map_or(false, |s| *s.as_bytes().last().unwrap() == b'&')
2251 p.span.shrink_to_hi(),
2252 if let Ok(snip) = self.tcx.sess.source_map().span_to_next_source(p.span)
2253 && snip.starts_with(' ')
2257 format!("{new_lt} ")
2262 add_lt_suggs.push(Some((p.span.shrink_to_hi(), format!("<{new_lt}>"))));
2268 let labeled_user_string = match bound_kind {
2269 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
2270 GenericKind::Alias(ref p) => match p.kind(self.tcx) {
2271 ty::AliasKind::Projection => format!("the associated type `{}`", p),
2272 ty::AliasKind::Opaque => format!("the opaque type `{}`", p),
2276 if let Some(SubregionOrigin::CompareImplItemObligation {
2282 return self.report_extra_impl_obligation(
2286 &format!("`{}: {}`", bound_kind, sub),
2290 fn binding_suggestion<'tcx, S: fmt::Display>(
2291 err: &mut Diagnostic,
2292 type_param_span: Option<(Span, bool)>,
2293 bound_kind: GenericKind<'tcx>,
2295 add_lt_suggs: Vec<Option<(Span, String)>>,
2297 let msg = "consider adding an explicit lifetime bound";
2298 if let Some((sp, has_lifetimes)) = type_param_span {
2300 if has_lifetimes { format!(" + {}", sub) } else { format!(": {}", sub) };
2301 let mut suggestions = vec![(sp, suggestion)];
2302 for add_lt_sugg in add_lt_suggs {
2303 if let Some(add_lt_sugg) = add_lt_sugg {
2304 suggestions.push(add_lt_sugg);
2307 err.multipart_suggestion_verbose(
2308 format!("{msg}..."),
2310 Applicability::MaybeIncorrect, // Issue #41966
2313 let consider = format!("{} `{}: {}`...", msg, bound_kind, sub);
2314 err.help(&consider);
2318 let new_binding_suggestion =
2319 |err: &mut Diagnostic, type_param_span: Option<(Span, bool)>| {
2320 let msg = "consider introducing an explicit lifetime bound";
2321 if let Some((sp, has_lifetimes)) = type_param_span {
2322 let suggestion = if has_lifetimes {
2323 format!(" + {}", new_lt)
2325 format!(": {}", new_lt)
2328 vec![(sp, suggestion), (span.shrink_to_hi(), format!(" + {}", new_lt))];
2329 for add_lt_sugg in add_lt_suggs.clone() {
2330 if let Some(lt) = add_lt_sugg {
2332 sugg.rotate_right(1);
2335 // `MaybeIncorrect` due to issue #41966.
2336 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2341 enum SubOrigin<'hir> {
2342 GAT(&'hir hir::Generics<'hir>),
2348 let sub_origin = 'origin: {
2350 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
2351 let node = self.tcx.hir().get_if_local(def_id).unwrap();
2353 Node::GenericParam(param) => {
2354 for h in self.tcx.hir().parent_iter(param.hir_id) {
2355 break 'origin match h.1 {
2356 Node::ImplItem(hir::ImplItem {
2357 kind: hir::ImplItemKind::Type(..),
2361 | Node::TraitItem(hir::TraitItem {
2362 kind: hir::TraitItemKind::Type(..),
2365 }) => SubOrigin::GAT(generics),
2366 Node::ImplItem(hir::ImplItem {
2367 kind: hir::ImplItemKind::Fn(..),
2370 | Node::TraitItem(hir::TraitItem {
2371 kind: hir::TraitItemKind::Fn(..),
2374 | Node::Item(hir::Item {
2375 kind: hir::ItemKind::Fn(..), ..
2376 }) => SubOrigin::Fn,
2377 Node::Item(hir::Item {
2378 kind: hir::ItemKind::Trait(..),
2380 }) => SubOrigin::Trait,
2381 Node::Item(hir::Item {
2382 kind: hir::ItemKind::Impl(..), ..
2383 }) => SubOrigin::Impl,
2395 debug!(?sub_origin);
2397 let mut err = match (*sub, sub_origin) {
2398 // In the case of GATs, we have to be careful. If we a type parameter `T` on an impl,
2399 // but a lifetime `'a` on an associated type, then we might need to suggest adding
2400 // `where T: 'a`. Importantly, this is on the GAT span, not on the `T` declaration.
2401 (ty::ReEarlyBound(ty::EarlyBoundRegion { name: _, .. }), SubOrigin::GAT(generics)) => {
2402 // Does the required lifetime have a nice name we can print?
2403 let mut err = struct_span_err!(
2407 "{} may not live long enough",
2410 let pred = format!("{}: {}", bound_kind, sub);
2411 let suggestion = format!("{} {}", generics.add_where_or_trailing_comma(), pred,);
2412 err.span_suggestion(
2413 generics.tail_span_for_predicate_suggestion(),
2414 "consider adding a where clause",
2416 Applicability::MaybeIncorrect,
2421 ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
2422 | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }),
2424 ) if name != kw::UnderscoreLifetime => {
2425 // Does the required lifetime have a nice name we can print?
2426 let mut err = struct_span_err!(
2430 "{} may not live long enough",
2433 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
2434 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
2435 // uses `Debug` output, so we handle it specially here so that suggestions are
2437 binding_suggestion(&mut err, type_param_span, bound_kind, name, vec![]);
2441 (ty::ReStatic, _) => {
2442 // Does the required lifetime have a nice name we can print?
2443 let mut err = struct_span_err!(
2447 "{} may not live long enough",
2450 binding_suggestion(&mut err, type_param_span, bound_kind, "'static", vec![]);
2455 // If not, be less specific.
2456 let mut err = struct_span_err!(
2460 "{} may not live long enough",
2463 note_and_explain_region(
2466 &format!("{} must be valid for ", labeled_user_string),
2471 if let Some(infer::RelateParamBound(_, t, _)) = origin {
2472 let return_impl_trait =
2473 self.tcx.return_type_impl_trait(generic_param_scope).is_some();
2474 let t = self.resolve_vars_if_possible(t);
2477 // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
2479 // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
2480 ty::Closure(..) | ty::Alias(ty::Opaque, ..) if return_impl_trait => {
2481 new_binding_suggestion(&mut err, type_param_span);
2498 if let Some(origin) = origin {
2499 self.note_region_origin(&mut err, &origin);
2504 fn report_sub_sup_conflict(
2506 var_origin: RegionVariableOrigin,
2507 sub_origin: SubregionOrigin<'tcx>,
2508 sub_region: Region<'tcx>,
2509 sup_origin: SubregionOrigin<'tcx>,
2510 sup_region: Region<'tcx>,
2512 let mut err = self.report_inference_failure(var_origin);
2514 note_and_explain_region(
2517 "first, the lifetime cannot outlive ",
2523 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
2524 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
2525 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
2526 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
2527 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
2529 if let infer::Subtype(ref sup_trace) = sup_origin
2530 && let infer::Subtype(ref sub_trace) = sub_origin
2531 && let Some((sup_expected, sup_found, _, _)) = self.values_str(sup_trace.values)
2532 && let Some((sub_expected, sub_found, _, _)) = self.values_str(sub_trace.values)
2533 && sub_expected == sup_expected
2534 && sub_found == sup_found
2536 note_and_explain_region(
2539 "...but the lifetime must also be valid for ",
2545 sup_trace.cause.span,
2546 &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
2549 err.note_expected_found(&"", sup_expected, &"", sup_found);
2554 self.note_region_origin(&mut err, &sup_origin);
2556 note_and_explain_region(
2559 "but, the lifetime must be valid for ",
2565 self.note_region_origin(&mut err, &sub_origin);
2569 /// Determine whether an error associated with the given span and definition
2570 /// should be treated as being caused by the implicit `From` conversion
2571 /// within `?` desugaring.
2572 pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2573 span.is_desugaring(DesugaringKind::QuestionMark)
2574 && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2577 /// Structurally compares two types, modulo any inference variables.
2579 /// Returns `true` if two types are equal, or if one type is an inference variable compatible
2580 /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
2581 /// FloatVar inference type are compatible with themselves or their concrete types (Int and
2582 /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
2583 pub fn same_type_modulo_infer<T: relate::Relate<'tcx>>(&self, a: T, b: T) -> bool {
2584 let (a, b) = self.resolve_vars_if_possible((a, b));
2585 SameTypeModuloInfer(self).relate(a, b).is_ok()
2589 struct SameTypeModuloInfer<'a, 'tcx>(&'a InferCtxt<'tcx>);
2591 impl<'tcx> TypeRelation<'tcx> for SameTypeModuloInfer<'_, 'tcx> {
2592 fn tcx(&self) -> TyCtxt<'tcx> {
2596 fn intercrate(&self) -> bool {
2597 assert!(!self.0.intercrate);
2601 fn param_env(&self) -> ty::ParamEnv<'tcx> {
2602 // Unused, only for consts which we treat as always equal
2603 ty::ParamEnv::empty()
2606 fn tag(&self) -> &'static str {
2607 "SameTypeModuloInfer"
2610 fn a_is_expected(&self) -> bool {
2614 fn mark_ambiguous(&mut self) {
2618 fn relate_with_variance<T: relate::Relate<'tcx>>(
2620 _variance: ty::Variance,
2621 _info: ty::VarianceDiagInfo<'tcx>,
2624 ) -> relate::RelateResult<'tcx, T> {
2628 fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> {
2629 match (a.kind(), b.kind()) {
2630 (ty::Int(_) | ty::Uint(_), ty::Infer(ty::InferTy::IntVar(_)))
2632 ty::Infer(ty::InferTy::IntVar(_)),
2633 ty::Int(_) | ty::Uint(_) | ty::Infer(ty::InferTy::IntVar(_)),
2635 | (ty::Float(_), ty::Infer(ty::InferTy::FloatVar(_)))
2637 ty::Infer(ty::InferTy::FloatVar(_)),
2638 ty::Float(_) | ty::Infer(ty::InferTy::FloatVar(_)),
2640 | (ty::Infer(ty::InferTy::TyVar(_)), _)
2641 | (_, ty::Infer(ty::InferTy::TyVar(_))) => Ok(a),
2642 (ty::Infer(_), _) | (_, ty::Infer(_)) => Err(TypeError::Mismatch),
2643 _ => relate::super_relate_tys(self, a, b),
2649 a: ty::Region<'tcx>,
2650 b: ty::Region<'tcx>,
2651 ) -> RelateResult<'tcx, ty::Region<'tcx>> {
2652 if (a.is_var() && b.is_free_or_static())
2653 || (b.is_var() && a.is_free_or_static())
2654 || (a.is_var() && b.is_var())
2659 Err(TypeError::Mismatch)
2665 a: ty::Binder<'tcx, T>,
2666 b: ty::Binder<'tcx, T>,
2667 ) -> relate::RelateResult<'tcx, ty::Binder<'tcx, T>>
2669 T: relate::Relate<'tcx>,
2671 Ok(a.rebind(self.relate(a.skip_binder(), b.skip_binder())?))
2677 _b: ty::Const<'tcx>,
2678 ) -> relate::RelateResult<'tcx, ty::Const<'tcx>> {
2679 // FIXME(compiler-errors): This could at least do some first-order
2685 impl<'tcx> InferCtxt<'tcx> {
2686 fn report_inference_failure(
2688 var_origin: RegionVariableOrigin,
2689 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2690 let br_string = |br: ty::BoundRegionKind| {
2691 let mut s = match br {
2692 ty::BrNamed(_, name) => name.to_string(),
2700 let var_description = match var_origin {
2701 infer::MiscVariable(_) => String::new(),
2702 infer::PatternRegion(_) => " for pattern".to_string(),
2703 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2704 infer::Autoref(_) => " for autoref".to_string(),
2705 infer::Coercion(_) => " for automatic coercion".to_string(),
2706 infer::LateBoundRegion(_, br, infer::FnCall) => {
2707 format!(" for lifetime parameter {}in function call", br_string(br))
2709 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2710 format!(" for lifetime parameter {}in generic type", br_string(br))
2712 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2713 " for lifetime parameter {}in trait containing associated type `{}`",
2715 self.tcx.associated_item(def_id).name
2717 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2718 infer::UpvarRegion(ref upvar_id, _) => {
2719 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2720 format!(" for capture of `{}` by closure", var_name)
2722 infer::Nll(..) => bug!("NLL variable found in lexical phase"),
2729 "cannot infer an appropriate lifetime{} due to conflicting requirements",
2735 pub enum FailureCode {
2737 Error0317(&'static str),
2738 Error0580(&'static str),
2739 Error0308(&'static str),
2740 Error0644(&'static str),
2743 pub trait ObligationCauseExt<'tcx> {
2744 fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode;
2745 fn as_requirement_str(&self) -> &'static str;
2748 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2749 fn as_failure_code(&self, terr: TypeError<'tcx>) -> FailureCode {
2750 use self::FailureCode::*;
2751 use crate::traits::ObligationCauseCode::*;
2753 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
2754 Error0308("method not compatible with trait")
2756 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
2757 Error0308("type not compatible with trait")
2759 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
2760 Error0308("const not compatible with trait")
2762 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
2763 Error0308(match source {
2764 hir::MatchSource::TryDesugar => "`?` operator has incompatible types",
2765 _ => "`match` arms have incompatible types",
2768 IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
2769 IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
2770 LetElse => Error0308("`else` clause of `let...else` does not diverge"),
2771 MainFunctionType => Error0580("`main` function has wrong type"),
2772 StartFunctionType => Error0308("`#[start]` function has wrong type"),
2773 IntrinsicType => Error0308("intrinsic has wrong type"),
2774 MethodReceiver => Error0308("mismatched `self` parameter type"),
2776 // In the case where we have no more specific thing to
2777 // say, also take a look at the error code, maybe we can
2780 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
2781 Error0644("closure/generator type that references itself")
2783 TypeError::IntrinsicCast => {
2784 Error0308("cannot coerce intrinsics to function pointers")
2786 _ => Error0308("mismatched types"),
2791 fn as_requirement_str(&self) -> &'static str {
2792 use crate::traits::ObligationCauseCode::*;
2794 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => {
2795 "method type is compatible with trait"
2797 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => {
2798 "associated type is compatible with trait"
2800 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => {
2801 "const is compatible with trait"
2803 ExprAssignable => "expression is assignable",
2804 IfExpression { .. } => "`if` and `else` have incompatible types",
2805 IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
2806 MainFunctionType => "`main` function has the correct type",
2807 StartFunctionType => "`#[start]` function has the correct type",
2808 IntrinsicType => "intrinsic has the correct type",
2809 MethodReceiver => "method receiver has the correct type",
2810 _ => "types are compatible",
2815 /// Newtype to allow implementing IntoDiagnosticArg
2816 pub struct ObligationCauseAsDiagArg<'tcx>(pub ObligationCause<'tcx>);
2818 impl IntoDiagnosticArg for ObligationCauseAsDiagArg<'_> {
2819 fn into_diagnostic_arg(self) -> rustc_errors::DiagnosticArgValue<'static> {
2820 use crate::traits::ObligationCauseCode::*;
2821 let kind = match self.0.code() {
2822 CompareImplItemObligation { kind: ty::AssocKind::Fn, .. } => "method_compat",
2823 CompareImplItemObligation { kind: ty::AssocKind::Type, .. } => "type_compat",
2824 CompareImplItemObligation { kind: ty::AssocKind::Const, .. } => "const_compat",
2825 ExprAssignable => "expr_assignable",
2826 IfExpression { .. } => "if_else_different",
2827 IfExpressionWithNoElse => "no_else",
2828 MainFunctionType => "fn_main_correct_type",
2829 StartFunctionType => "fn_start_correct_type",
2830 IntrinsicType => "intristic_correct_type",
2831 MethodReceiver => "method_correct_type",
2835 rustc_errors::DiagnosticArgValue::Str(kind)
2839 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2840 /// extra information about each type, but we only care about the category.
2841 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2842 pub enum TyCategory {
2845 Generator(hir::GeneratorKind),
2850 fn descr(&self) -> &'static str {
2852 Self::Closure => "closure",
2853 Self::Opaque => "opaque type",
2854 Self::Generator(gk) => gk.descr(),
2855 Self::Foreign => "foreign type",
2859 pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2861 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2862 ty::Alias(ty::Opaque, ty::AliasTy { def_id, .. }) => Some((Self::Opaque, def_id)),
2863 ty::Generator(def_id, ..) => {
2864 Some((Self::Generator(tcx.generator_kind(def_id).unwrap()), def_id))
2866 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),
2872 impl<'tcx> InferCtxt<'tcx> {
2873 /// Given a [`hir::Block`], get the span of its last expression or
2874 /// statement, peeling off any inner blocks.
2875 pub fn find_block_span(&self, block: &'tcx hir::Block<'tcx>) -> Span {
2876 let block = block.innermost_block();
2877 if let Some(expr) = &block.expr {
2879 } else if let Some(stmt) = block.stmts.last() {
2880 // possibly incorrect trailing `;` in the else arm
2883 // empty block; point at its entirety
2888 /// Given a [`hir::HirId`] for a block, get the span of its last expression
2889 /// or statement, peeling off any inner blocks.
2890 pub fn find_block_span_from_hir_id(&self, hir_id: hir::HirId) -> Span {
2891 match self.tcx.hir().get(hir_id) {
2892 hir::Node::Block(blk) => self.find_block_span(blk),
2893 // The parser was in a weird state if either of these happen, but
2894 // it's better not to panic.
2895 hir::Node::Expr(e) => e.span,
2896 _ => rustc_span::DUMMY_SP,