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::traits::error_reporting::report_object_safety_error;
56 IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
57 StatementAsExpression,
60 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
61 use rustc_errors::{pluralize, struct_span_err, Diagnostic, ErrorGuaranteed};
62 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString, MultiSpan};
64 use rustc_hir::def_id::{DefId, LocalDefId};
65 use rustc_hir::lang_items::LangItem;
67 use rustc_middle::dep_graph::DepContext;
68 use rustc_middle::ty::print::with_no_trimmed_paths;
69 use rustc_middle::ty::{
70 self, error::TypeError, Binder, List, Region, Subst, Ty, TyCtxt, TypeFoldable,
71 TypeSuperVisitable, TypeVisitable,
73 use rustc_span::{sym, symbol::kw, BytePos, DesugaringKind, Pos, Span};
74 use rustc_target::spec::abi;
75 use std::ops::ControlFlow;
76 use std::{cmp, fmt, iter};
81 pub use need_type_info::TypeAnnotationNeeded;
83 pub mod nice_region_error;
85 pub(super) fn note_and_explain_region<'tcx>(
89 region: ty::Region<'tcx>,
91 alt_span: Option<Span>,
93 let (description, span) = match *region {
94 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
95 msg_span_from_free_region(tcx, region, alt_span)
98 ty::ReEmpty(ty::UniverseIndex::ROOT) => ("the empty lifetime".to_owned(), alt_span),
100 // uh oh, hope no user ever sees THIS
101 ty::ReEmpty(ui) => (format!("the empty lifetime in universe {:?}", ui), alt_span),
103 ty::RePlaceholder(_) => return,
105 // FIXME(#13998) RePlaceholder should probably print like
106 // ReFree rather than dumping Debug output on the user.
108 // We shouldn't really be having unification failures with ReVar
109 // and ReLateBound though.
110 ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
111 (format!("lifetime {:?}", region), alt_span)
115 emit_msg_span(err, prefix, description, span, suffix);
118 fn explain_free_region<'tcx>(
120 err: &mut Diagnostic,
122 region: ty::Region<'tcx>,
125 let (description, span) = msg_span_from_free_region(tcx, region, None);
127 label_msg_span(err, prefix, description, span, suffix);
130 fn msg_span_from_free_region<'tcx>(
132 region: ty::Region<'tcx>,
133 alt_span: Option<Span>,
134 ) -> (String, Option<Span>) {
136 ty::ReEarlyBound(_) | ty::ReFree(_) => {
137 let (msg, span) = msg_span_from_early_bound_and_free_regions(tcx, region);
140 ty::ReStatic => ("the static lifetime".to_owned(), alt_span),
141 ty::ReEmpty(ty::UniverseIndex::ROOT) => ("an empty lifetime".to_owned(), alt_span),
142 ty::ReEmpty(ui) => (format!("an empty lifetime in universe {:?}", ui), alt_span),
143 _ => bug!("{:?}", region),
147 fn msg_span_from_early_bound_and_free_regions<'tcx>(
149 region: ty::Region<'tcx>,
150 ) -> (String, Span) {
151 let scope = region.free_region_binding_scope(tcx).expect_local();
153 ty::ReEarlyBound(ref br) => {
154 let mut sp = tcx.def_span(scope);
156 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
160 let text = if br.has_name() {
161 format!("the lifetime `{}` as defined here", br.name)
163 format!("the anonymous lifetime as defined here")
167 ty::ReFree(ref fr) => {
168 if !fr.bound_region.is_named()
169 && let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region)
171 ("the anonymous lifetime defined here".to_string(), ty.span)
173 match fr.bound_region {
174 ty::BoundRegionKind::BrNamed(_, name) => {
175 let mut sp = tcx.def_span(scope);
177 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
181 let text = if name == kw::UnderscoreLifetime {
182 format!("the anonymous lifetime as defined here")
184 format!("the lifetime `{}` as defined here", name)
189 format!("the anonymous lifetime #{} defined here", idx + 1),
193 format!("the lifetime `{}` as defined here", region),
204 err: &mut Diagnostic,
210 let message = format!("{}{}{}", prefix, description, suffix);
212 if let Some(span) = span {
213 err.span_note(span, &message);
220 err: &mut Diagnostic,
226 let message = format!("{}{}{}", prefix, description, suffix);
228 if let Some(span) = span {
229 err.span_label(span, &message);
235 pub fn unexpected_hidden_region_diagnostic<'tcx>(
239 hidden_region: ty::Region<'tcx>,
240 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
241 let mut err = struct_span_err!(
245 "hidden type for `impl Trait` captures lifetime that does not appear in bounds",
248 // Explain the region we are capturing.
249 match *hidden_region {
250 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
251 // All lifetimes shorter than the function body are `empty` in
252 // lexical region resolution. The default explanation of "an empty
253 // lifetime" isn't really accurate here.
254 let message = format!(
255 "hidden type `{}` captures lifetime smaller than the function body",
258 err.span_note(span, &message);
260 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty(_) => {
261 // Assuming regionck succeeded (*), we ought to always be
262 // capturing *some* region from the fn header, and hence it
263 // ought to be free. So under normal circumstances, we will go
264 // down this path which gives a decent human readable
267 // (*) if not, the `tainted_by_errors` field would be set to
268 // `Some(ErrorGuaranteed)` in any case, so we wouldn't be here at all.
272 &format!("hidden type `{}` captures ", hidden_ty),
276 if let Some(reg_info) = tcx.is_suitable_region(hidden_region) {
277 let fn_returns = tcx.return_type_impl_or_dyn_traits(reg_info.def_id);
278 nice_region_error::suggest_new_region_bound(
282 hidden_region.to_string(),
284 format!("captures `{}`", hidden_region),
290 // Ugh. This is a painful case: the hidden region is not one
291 // that we can easily summarize or explain. This can happen
293 // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
296 // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
297 // if condition() { a } else { b }
301 // Here the captured lifetime is the intersection of `'a` and
302 // `'b`, which we can't quite express.
304 // We can at least report a really cryptic error for now.
305 note_and_explain_region(
308 &format!("hidden type `{}` captures ", hidden_ty),
319 /// Structurally compares two types, modulo any inference variables.
321 /// Returns `true` if two types are equal, or if one type is an inference variable compatible
322 /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
323 /// FloatVar inference type are compatible with themselves or their concrete types (Int and
324 /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
325 pub fn same_type_modulo_infer<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
326 match (&a.kind(), &b.kind()) {
327 (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
332 substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type_modulo_infer(a, b))
334 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
335 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)))
336 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
338 &ty::Infer(ty::InferTy::FloatVar(_)),
339 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
341 | (&ty::Infer(ty::InferTy::TyVar(_)), _)
342 | (_, &ty::Infer(ty::InferTy::TyVar(_))) => true,
343 (&ty::Ref(_, ty_a, mut_a), &ty::Ref(_, ty_b, mut_b)) => {
344 mut_a == mut_b && same_type_modulo_infer(*ty_a, *ty_b)
350 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
351 pub fn report_region_errors(
353 generic_param_scope: LocalDefId,
354 errors: &[RegionResolutionError<'tcx>],
356 debug!("report_region_errors(): {} errors to start", errors.len());
358 // try to pre-process the errors, which will group some of them
359 // together into a `ProcessedErrors` group:
360 let errors = self.process_errors(errors);
362 debug!("report_region_errors: {} errors after preprocessing", errors.len());
364 for error in errors {
365 debug!("report_region_errors: error = {:?}", error);
367 if !self.try_report_nice_region_error(&error) {
368 match error.clone() {
369 // These errors could indicate all manner of different
370 // problems with many different solutions. Rather
371 // than generate a "one size fits all" error, what we
372 // attempt to do is go through a number of specific
373 // scenarios and try to find the best way to present
374 // the error. If all of these fails, we fall back to a rather
375 // general bit of code that displays the error information
376 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
377 if sub.is_placeholder() || sup.is_placeholder() {
378 self.report_placeholder_failure(origin, sub, sup).emit();
380 self.report_concrete_failure(origin, sub, sup).emit();
384 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
385 self.report_generic_bound_failure(
394 RegionResolutionError::SubSupConflict(
403 if sub_r.is_placeholder() {
404 self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
405 } else if sup_r.is_placeholder() {
406 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
408 self.report_sub_sup_conflict(
409 var_origin, sub_origin, sub_r, sup_origin, sup_r,
414 RegionResolutionError::UpperBoundUniverseConflict(
421 assert!(sup_r.is_placeholder());
423 // Make a dummy value for the "sub region" --
424 // this is the initial value of the
425 // placeholder. In practice, we expect more
426 // tailored errors that don't really use this
428 let sub_r = self.tcx.mk_region(ty::ReEmpty(var_universe));
430 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
437 // This method goes through all the errors and try to group certain types
438 // of error together, for the purpose of suggesting explicit lifetime
439 // parameters to the user. This is done so that we can have a more
440 // complete view of what lifetimes should be the same.
441 // If the return value is an empty vector, it means that processing
442 // failed (so the return value of this method should not be used).
444 // The method also attempts to weed out messages that seem like
445 // duplicates that will be unhelpful to the end-user. But
446 // obviously it never weeds out ALL errors.
449 errors: &[RegionResolutionError<'tcx>],
450 ) -> Vec<RegionResolutionError<'tcx>> {
451 debug!("process_errors()");
453 // We want to avoid reporting generic-bound failures if we can
454 // avoid it: these have a very high rate of being unhelpful in
455 // practice. This is because they are basically secondary
456 // checks that test the state of the region graph after the
457 // rest of inference is done, and the other kinds of errors
458 // indicate that the region constraint graph is internally
459 // inconsistent, so these test results are likely to be
462 // Therefore, we filter them out of the list unless they are
463 // the only thing in the list.
465 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
466 RegionResolutionError::GenericBoundFailure(..) => true,
467 RegionResolutionError::ConcreteFailure(..)
468 | RegionResolutionError::SubSupConflict(..)
469 | RegionResolutionError::UpperBoundUniverseConflict(..) => false,
472 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
475 errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
478 // sort the errors by span, for better error message stability.
479 errors.sort_by_key(|u| match *u {
480 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
481 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
482 RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(),
483 RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
488 /// Adds a note if the types come from similarly named crates
489 fn check_and_note_conflicting_crates(&self, err: &mut Diagnostic, terr: &TypeError<'tcx>) {
490 use hir::def_id::CrateNum;
491 use rustc_hir::definitions::DisambiguatedDefPathData;
492 use ty::print::Printer;
493 use ty::subst::GenericArg;
495 struct AbsolutePathPrinter<'tcx> {
499 struct NonTrivialPath;
501 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
502 type Error = NonTrivialPath;
504 type Path = Vec<String>;
507 type DynExistential = !;
510 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
514 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
518 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
522 fn print_dyn_existential(
524 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
525 ) -> Result<Self::DynExistential, Self::Error> {
529 fn print_const(self, _ct: ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
533 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
534 Ok(vec![self.tcx.crate_name(cnum).to_string()])
539 _trait_ref: Option<ty::TraitRef<'tcx>>,
540 ) -> Result<Self::Path, Self::Error> {
546 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
547 _disambiguated_data: &DisambiguatedDefPathData,
549 _trait_ref: Option<ty::TraitRef<'tcx>>,
550 ) -> Result<Self::Path, Self::Error> {
555 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
556 disambiguated_data: &DisambiguatedDefPathData,
557 ) -> Result<Self::Path, Self::Error> {
558 let mut path = print_prefix(self)?;
559 path.push(disambiguated_data.to_string());
562 fn path_generic_args(
564 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
565 _args: &[GenericArg<'tcx>],
566 ) -> Result<Self::Path, Self::Error> {
571 let report_path_match = |err: &mut Diagnostic, did1: DefId, did2: DefId| {
572 // Only external crates, if either is from a local
573 // module we could have false positives
574 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
576 |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
578 // We compare strings because DefPath can be different
579 // for imported and non-imported crates
580 let same_path = || -> Result<_, NonTrivialPath> {
581 Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
582 || abs_path(did1)? == abs_path(did2)?)
584 if same_path().unwrap_or(false) {
585 let crate_name = self.tcx.crate_name(did1.krate);
587 "perhaps two different versions of crate `{}` are being used?",
594 TypeError::Sorts(ref exp_found) => {
595 // if they are both "path types", there's a chance of ambiguity
596 // due to different versions of the same crate
597 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
598 (exp_found.expected.kind(), exp_found.found.kind())
600 report_path_match(err, exp_adt.did(), found_adt.did());
603 TypeError::Traits(ref exp_found) => {
604 report_path_match(err, exp_found.expected, exp_found.found);
606 _ => (), // FIXME(#22750) handle traits and stuff
610 fn note_error_origin(
612 err: &mut Diagnostic,
613 cause: &ObligationCause<'tcx>,
614 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
615 terr: &TypeError<'tcx>,
617 match *cause.code() {
618 ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
619 let ty = self.resolve_vars_if_possible(root_ty);
620 if !matches!(ty.kind(), ty::Infer(ty::InferTy::TyVar(_) | ty::InferTy::FreshTy(_)))
622 // don't show type `_`
623 if span.desugaring_kind() == Some(DesugaringKind::ForLoop)
624 && let ty::Adt(def, substs) = ty.kind()
625 && Some(def.did()) == self.tcx.get_diagnostic_item(sym::Option)
627 err.span_label(span, format!("this is an iterator with items of type `{}`", substs.type_at(0)));
629 err.span_label(span, format!("this expression has type `{}`", ty));
632 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found
633 && ty.is_box() && ty.boxed_ty() == found
634 && let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span)
638 "consider dereferencing the boxed value",
639 format!("*{}", snippet),
640 Applicability::MachineApplicable,
644 ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
645 err.span_label(span, "expected due to this");
647 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
653 opt_suggest_box_span,
658 hir::MatchSource::TryDesugar => {
659 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
660 let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
661 let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
662 let arg_expr = args.first().expect("try desugaring call w/out arg");
663 self.in_progress_typeck_results.and_then(|typeck_results| {
664 typeck_results.borrow().expr_ty_opt(arg_expr)
667 bug!("try desugaring w/out call expr as scrutinee");
671 Some(ty) if expected == ty => {
672 let source_map = self.tcx.sess.source_map();
674 source_map.end_point(cause.span),
675 "try removing this `?`",
677 Applicability::MachineApplicable,
685 // `last_ty` can be `!`, `expected` will have better info when present.
686 let t = self.resolve_vars_if_possible(match exp_found {
687 Some(ty::error::ExpectedFound { expected, .. }) => expected,
690 let source_map = self.tcx.sess.source_map();
691 let mut any_multiline_arm = source_map.is_multiline(arm_span);
692 if prior_arms.len() <= 4 {
693 for sp in prior_arms {
694 any_multiline_arm |= source_map.is_multiline(*sp);
695 err.span_label(*sp, format!("this is found to be of type `{}`", t));
697 } else if let Some(sp) = prior_arms.last() {
698 any_multiline_arm |= source_map.is_multiline(*sp);
701 format!("this and all prior arms are found to be of type `{}`", t),
704 let outer_error_span = if any_multiline_arm {
705 // Cover just `match` and the scrutinee expression, not
706 // the entire match body, to reduce diagram noise.
707 cause.span.shrink_to_lo().to(scrut_span)
711 let msg = "`match` arms have incompatible types";
712 err.span_label(outer_error_span, msg);
713 if let Some((sp, boxed)) = semi_span {
714 if let (StatementAsExpression::NeedsBoxing, [.., prior_arm]) =
715 (boxed, &prior_arms[..])
717 err.multipart_suggestion(
718 "consider removing this semicolon and boxing the expressions",
720 (prior_arm.shrink_to_lo(), "Box::new(".to_string()),
721 (prior_arm.shrink_to_hi(), ")".to_string()),
722 (arm_span.shrink_to_lo(), "Box::new(".to_string()),
723 (arm_span.shrink_to_hi(), ")".to_string()),
726 Applicability::HasPlaceholders,
728 } else if matches!(boxed, StatementAsExpression::NeedsBoxing) {
729 err.span_suggestion_short(
731 "consider removing this semicolon and boxing the expressions",
733 Applicability::MachineApplicable,
736 err.span_suggestion_short(
738 "consider removing this semicolon",
740 Applicability::MachineApplicable,
744 if let Some(ret_sp) = opt_suggest_box_span {
745 // Get return type span and point to it.
746 self.suggest_boxing_for_return_impl_trait(
749 prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
754 ObligationCauseCode::IfExpression(box IfExpressionCause {
759 opt_suggest_box_span,
761 err.span_label(then, "expected because of this");
762 if let Some(sp) = outer {
763 err.span_label(sp, "`if` and `else` have incompatible types");
765 if let Some((sp, boxed)) = semicolon {
766 if matches!(boxed, StatementAsExpression::NeedsBoxing) {
767 err.multipart_suggestion(
768 "consider removing this semicolon and boxing the expression",
770 (then.shrink_to_lo(), "Box::new(".to_string()),
771 (then.shrink_to_hi(), ")".to_string()),
772 (else_sp.shrink_to_lo(), "Box::new(".to_string()),
773 (else_sp.shrink_to_hi(), ")".to_string()),
776 Applicability::MachineApplicable,
779 err.span_suggestion_short(
781 "consider removing this semicolon",
783 Applicability::MachineApplicable,
787 if let Some(ret_sp) = opt_suggest_box_span {
788 self.suggest_boxing_for_return_impl_trait(
791 [then, else_sp].into_iter(),
795 ObligationCauseCode::LetElse => {
796 err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
797 err.help("...or use `match` instead of `let...else`");
800 if let ObligationCauseCode::BindingObligation(_, binding_span) =
801 cause.code().peel_derives()
803 if matches!(terr, TypeError::RegionsPlaceholderMismatch) {
804 err.span_note(*binding_span, "the lifetime requirement is introduced here");
811 fn suggest_boxing_for_return_impl_trait(
813 err: &mut Diagnostic,
815 arm_spans: impl Iterator<Item = Span>,
817 err.multipart_suggestion(
818 "you could change the return type to be a boxed trait object",
820 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
821 (return_sp.shrink_to_hi(), ">".to_string()),
823 Applicability::MaybeIncorrect,
827 [(sp.shrink_to_lo(), "Box::new(".to_string()), (sp.shrink_to_hi(), ")".to_string())]
830 .collect::<Vec<_>>();
831 err.multipart_suggestion(
832 "if you change the return type to expect trait objects, box the returned expressions",
834 Applicability::MaybeIncorrect,
838 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
839 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
840 /// populate `other_value` with `other_ty`.
844 /// ^^^^--------^ this is highlighted
846 /// | this type argument is exactly the same as the other type, not highlighted
847 /// this is highlighted
849 /// -------- this type is the same as a type argument in the other type, not highlighted
853 value: &mut DiagnosticStyledString,
854 other_value: &mut DiagnosticStyledString,
856 sub: ty::subst::SubstsRef<'tcx>,
860 // `value` and `other_value` hold two incomplete type representation for display.
861 // `name` is the path of both types being compared. `sub`
862 value.push_highlighted(name);
865 value.push_highlighted("<");
868 // Output the lifetimes for the first type
872 let s = lifetime.to_string();
873 if s.is_empty() { "'_".to_string() } else { s }
877 if !lifetimes.is_empty() {
878 if sub.regions().count() < len {
879 value.push_normal(lifetimes + ", ");
881 value.push_normal(lifetimes);
885 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
886 // `pos` and `other_ty`.
887 for (i, type_arg) in sub.types().enumerate() {
889 let values = self.cmp(type_arg, other_ty);
890 value.0.extend((values.0).0);
891 other_value.0.extend((values.1).0);
893 value.push_highlighted(type_arg.to_string());
896 if len > 0 && i != len - 1 {
897 value.push_normal(", ");
901 value.push_highlighted(">");
905 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
906 /// as that is the difference to the other type.
908 /// For the following code:
910 /// ```ignore (illustrative)
911 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
914 /// The type error output will behave in the following way:
918 /// ^^^^--------^ this is highlighted
920 /// | this type argument is exactly the same as the other type, not highlighted
921 /// this is highlighted
923 /// -------- this type is the same as a type argument in the other type, not highlighted
927 mut t1_out: &mut DiagnosticStyledString,
928 mut t2_out: &mut DiagnosticStyledString,
930 sub: &'tcx [ty::GenericArg<'tcx>],
934 // FIXME/HACK: Go back to `SubstsRef` to use its inherent methods,
935 // ideally that shouldn't be necessary.
936 let sub = self.tcx.intern_substs(sub);
937 for (i, ta) in sub.types().enumerate() {
939 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
942 if let ty::Adt(def, _) = ta.kind() {
943 let path_ = self.tcx.def_path_str(def.did());
944 if path_ == other_path {
945 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, other_ty);
953 /// Adds a `,` to the type representation only if it is appropriate.
956 value: &mut DiagnosticStyledString,
957 other_value: &mut DiagnosticStyledString,
961 if len > 0 && pos != len - 1 {
962 value.push_normal(", ");
963 other_value.push_normal(", ");
967 /// Given two `fn` signatures highlight only sub-parts that are different.
970 sig1: &ty::PolyFnSig<'tcx>,
971 sig2: &ty::PolyFnSig<'tcx>,
972 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
973 let get_lifetimes = |sig| {
974 use rustc_hir::def::Namespace;
975 let (_, sig, reg) = ty::print::FmtPrinter::new(self.tcx, Namespace::TypeNS)
976 .name_all_regions(sig)
978 let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
979 (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
982 let (lt1, sig1) = get_lifetimes(sig1);
983 let (lt2, sig2) = get_lifetimes(sig2);
985 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
987 DiagnosticStyledString::normal("".to_string()),
988 DiagnosticStyledString::normal("".to_string()),
991 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
993 values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
994 values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
996 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
998 if sig1.abi != abi::Abi::Rust {
999 values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
1001 if sig2.abi != abi::Abi::Rust {
1002 values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
1005 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1007 let lifetime_diff = lt1 != lt2;
1008 values.0.push(lt1, lifetime_diff);
1009 values.1.push(lt2, lifetime_diff);
1011 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1013 values.0.push_normal("fn(");
1014 values.1.push_normal("fn(");
1016 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1018 let len1 = sig1.inputs().len();
1019 let len2 = sig2.inputs().len();
1021 for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
1022 let (x1, x2) = self.cmp(*l, *r);
1023 (values.0).0.extend(x1.0);
1024 (values.1).0.extend(x2.0);
1025 self.push_comma(&mut values.0, &mut values.1, len1, i);
1028 for (i, l) in sig1.inputs().iter().enumerate() {
1029 values.0.push_highlighted(l.to_string());
1031 values.0.push_highlighted(", ");
1034 for (i, r) in sig2.inputs().iter().enumerate() {
1035 values.1.push_highlighted(r.to_string());
1037 values.1.push_highlighted(", ");
1042 if sig1.c_variadic {
1044 values.0.push_normal(", ");
1046 values.0.push("...", !sig2.c_variadic);
1048 if sig2.c_variadic {
1050 values.1.push_normal(", ");
1052 values.1.push("...", !sig1.c_variadic);
1055 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1057 values.0.push_normal(")");
1058 values.1.push_normal(")");
1060 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1062 let output1 = sig1.output();
1063 let output2 = sig2.output();
1064 let (x1, x2) = self.cmp(output1, output2);
1065 if !output1.is_unit() {
1066 values.0.push_normal(" -> ");
1067 (values.0).0.extend(x1.0);
1069 if !output2.is_unit() {
1070 values.1.push_normal(" -> ");
1071 (values.1).0.extend(x2.0);
1076 /// Compares two given types, eliding parts that are the same between them and highlighting
1077 /// relevant differences, and return two representation of those types for highlighted printing.
1082 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
1083 debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1086 fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1087 match (a.kind(), b.kind()) {
1088 (a, b) if *a == *b => true,
1089 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1091 &ty::Infer(ty::InferTy::IntVar(_)),
1092 &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1094 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1096 &ty::Infer(ty::InferTy::FloatVar(_)),
1097 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1103 fn push_ty_ref<'tcx>(
1104 region: ty::Region<'tcx>,
1106 mutbl: hir::Mutability,
1107 s: &mut DiagnosticStyledString,
1109 let mut r = region.to_string();
1115 s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1116 s.push_normal(ty.to_string());
1119 // process starts here
1120 match (t1.kind(), t2.kind()) {
1121 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1122 let did1 = def1.did();
1123 let did2 = def2.did();
1124 let sub_no_defaults_1 =
1125 self.tcx.generics_of(did1).own_substs_no_defaults(self.tcx, sub1);
1126 let sub_no_defaults_2 =
1127 self.tcx.generics_of(did2).own_substs_no_defaults(self.tcx, sub2);
1128 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1129 let path1 = self.tcx.def_path_str(did1);
1130 let path2 = self.tcx.def_path_str(did2);
1132 // Easy case. Replace same types with `_` to shorten the output and highlight
1133 // the differing ones.
1134 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1137 // --- ^ type argument elided
1139 // highlighted in output
1140 values.0.push_normal(path1);
1141 values.1.push_normal(path2);
1143 // Avoid printing out default generic parameters that are common to both
1145 let len1 = sub_no_defaults_1.len();
1146 let len2 = sub_no_defaults_2.len();
1147 let common_len = cmp::min(len1, len2);
1148 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1149 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1150 let common_default_params =
1151 iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1152 .filter(|(a, b)| a == b)
1154 let len = sub1.len() - common_default_params;
1155 let consts_offset = len - sub1.consts().count();
1157 // Only draw `<...>` if there are lifetime/type arguments.
1159 values.0.push_normal("<");
1160 values.1.push_normal("<");
1163 fn lifetime_display(lifetime: Region<'_>) -> String {
1164 let s = lifetime.to_string();
1165 if s.is_empty() { "'_".to_string() } else { s }
1167 // At one point we'd like to elide all lifetimes here, they are irrelevant for
1168 // all diagnostics that use this output
1172 // ^^ ^^ --- type arguments are not elided
1174 // | elided as they were the same
1175 // not elided, they were different, but irrelevant
1177 // For bound lifetimes, keep the names of the lifetimes,
1178 // even if they are the same so that it's clear what's happening
1179 // if we have something like
1181 // for<'r, 's> fn(Inv<'r>, Inv<'s>)
1182 // for<'r> fn(Inv<'r>, Inv<'r>)
1183 let lifetimes = sub1.regions().zip(sub2.regions());
1184 for (i, lifetimes) in lifetimes.enumerate() {
1185 let l1 = lifetime_display(lifetimes.0);
1186 let l2 = lifetime_display(lifetimes.1);
1187 if lifetimes.0 != lifetimes.1 {
1188 values.0.push_highlighted(l1);
1189 values.1.push_highlighted(l2);
1190 } else if lifetimes.0.is_late_bound() {
1191 values.0.push_normal(l1);
1192 values.1.push_normal(l2);
1194 values.0.push_normal("'_");
1195 values.1.push_normal("'_");
1197 self.push_comma(&mut values.0, &mut values.1, len, i);
1200 // We're comparing two types with the same path, so we compare the type
1201 // arguments for both. If they are the same, do not highlight and elide from the
1205 // ^ elided type as this type argument was the same in both sides
1206 let type_arguments = sub1.types().zip(sub2.types());
1207 let regions_len = sub1.regions().count();
1208 let num_display_types = consts_offset - regions_len;
1209 for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1210 let i = i + regions_len;
1212 values.0.push_normal("_");
1213 values.1.push_normal("_");
1215 let (x1, x2) = self.cmp(ta1, ta2);
1216 (values.0).0.extend(x1.0);
1217 (values.1).0.extend(x2.0);
1219 self.push_comma(&mut values.0, &mut values.1, len, i);
1222 // Do the same for const arguments, if they are equal, do not highlight and
1223 // elide them from the output.
1224 let const_arguments = sub1.consts().zip(sub2.consts());
1225 for (i, (ca1, ca2)) in const_arguments.enumerate() {
1226 let i = i + consts_offset;
1228 values.0.push_normal("_");
1229 values.1.push_normal("_");
1231 values.0.push_highlighted(ca1.to_string());
1232 values.1.push_highlighted(ca2.to_string());
1234 self.push_comma(&mut values.0, &mut values.1, len, i);
1237 // Close the type argument bracket.
1238 // Only draw `<...>` if there are lifetime/type arguments.
1240 values.0.push_normal(">");
1241 values.1.push_normal(">");
1246 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1248 // ------- this type argument is exactly the same as the other type
1264 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1267 // ------- this type argument is exactly the same as the other type
1282 // We can't find anything in common, highlight relevant part of type path.
1283 // let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1284 // foo::bar::Baz<Qux>
1285 // foo::bar::Bar<Zar>
1286 // -------- this part of the path is different
1288 let t1_str = t1.to_string();
1289 let t2_str = t2.to_string();
1290 let min_len = t1_str.len().min(t2_str.len());
1292 const SEPARATOR: &str = "::";
1293 let separator_len = SEPARATOR.len();
1294 let split_idx: usize =
1295 iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1296 .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1297 .map(|(mod_str, _)| mod_str.len() + separator_len)
1301 "cmp: separator_len={}, split_idx={}, min_len={}",
1302 separator_len, split_idx, min_len
1305 if split_idx >= min_len {
1306 // paths are identical, highlight everything
1308 DiagnosticStyledString::highlighted(t1_str),
1309 DiagnosticStyledString::highlighted(t2_str),
1312 let (common, uniq1) = t1_str.split_at(split_idx);
1313 let (_, uniq2) = t2_str.split_at(split_idx);
1314 debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1316 values.0.push_normal(common);
1317 values.0.push_highlighted(uniq1);
1318 values.1.push_normal(common);
1319 values.1.push_highlighted(uniq2);
1326 // When finding T != &T, highlight only the borrow
1327 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(ref_ty1, t2) => {
1328 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1329 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1330 values.1.push_normal(t2.to_string());
1333 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(t1, ref_ty2) => {
1334 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1335 values.0.push_normal(t1.to_string());
1336 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1340 // When encountering &T != &mut T, highlight only the borrow
1341 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1342 if equals(ref_ty1, ref_ty2) =>
1344 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1345 push_ty_ref(r1, ref_ty1, mutbl1, &mut values.0);
1346 push_ty_ref(r2, ref_ty2, mutbl2, &mut values.1);
1350 // When encountering tuples of the same size, highlight only the differing types
1351 (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1353 (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1354 let len = substs1.len();
1355 for (i, (left, right)) in substs1.iter().zip(substs2).enumerate() {
1356 let (x1, x2) = self.cmp(left, right);
1357 (values.0).0.extend(x1.0);
1358 (values.1).0.extend(x2.0);
1359 self.push_comma(&mut values.0, &mut values.1, len, i);
1362 // Keep the output for single element tuples as `(ty,)`.
1363 values.0.push_normal(",");
1364 values.1.push_normal(",");
1366 values.0.push_normal(")");
1367 values.1.push_normal(")");
1371 (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1372 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1373 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1374 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1375 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1376 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1377 let same_path = path1 == path2;
1378 values.0.push(path1, !same_path);
1379 values.1.push(path2, !same_path);
1383 (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1384 let sig1 = self.tcx.bound_fn_sig(*did1).subst(self.tcx, substs1);
1385 let mut values = self.cmp_fn_sig(&sig1, sig2);
1386 values.0.push_highlighted(format!(
1388 self.tcx.def_path_str_with_substs(*did1, substs1)
1393 (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1394 let sig2 = self.tcx.bound_fn_sig(*did2).subst(self.tcx, substs2);
1395 let mut values = self.cmp_fn_sig(sig1, &sig2);
1396 values.1.push_normal(format!(
1398 self.tcx.def_path_str_with_substs(*did2, substs2)
1403 (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1407 // The two types are the same, elide and don't highlight.
1408 (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1410 // We couldn't find anything in common, highlight everything.
1412 DiagnosticStyledString::highlighted(t1.to_string()),
1413 DiagnosticStyledString::highlighted(t2.to_string()),
1420 /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
1421 /// the return type of `async fn`s.
1423 /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1425 /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
1426 /// the message in `secondary_span` as the primary label, and apply the message that would
1427 /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
1428 /// E0271, like `src/test/ui/issues/issue-39970.stderr`.
1429 #[tracing::instrument(
1431 skip(self, diag, secondary_span, swap_secondary_and_primary, force_label)
1433 pub fn note_type_err(
1435 diag: &mut Diagnostic,
1436 cause: &ObligationCause<'tcx>,
1437 secondary_span: Option<(Span, String)>,
1438 mut values: Option<ValuePairs<'tcx>>,
1439 terr: &TypeError<'tcx>,
1440 swap_secondary_and_primary: bool,
1443 let span = cause.span();
1445 // For some types of errors, expected-found does not make
1446 // sense, so just ignore the values we were given.
1447 if let TypeError::CyclicTy(_) = terr {
1450 struct OpaqueTypesVisitor<'tcx> {
1451 types: FxHashMap<TyCategory, FxHashSet<Span>>,
1452 expected: FxHashMap<TyCategory, FxHashSet<Span>>,
1453 found: FxHashMap<TyCategory, FxHashSet<Span>>,
1458 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1459 fn visit_expected_found(
1465 let mut types_visitor = OpaqueTypesVisitor {
1466 types: Default::default(),
1467 expected: Default::default(),
1468 found: Default::default(),
1472 // The visitor puts all the relevant encountered types in `self.types`, but in
1473 // here we want to visit two separate types with no relation to each other, so we
1474 // move the results from `types` to `expected` or `found` as appropriate.
1475 expected.visit_with(&mut types_visitor);
1476 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1477 found.visit_with(&mut types_visitor);
1478 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1482 fn report(&self, err: &mut Diagnostic) {
1483 self.add_labels_for_types(err, "expected", &self.expected);
1484 self.add_labels_for_types(err, "found", &self.found);
1487 fn add_labels_for_types(
1489 err: &mut Diagnostic,
1491 types: &FxHashMap<TyCategory, FxHashSet<Span>>,
1493 for (key, values) in types.iter() {
1494 let count = values.len();
1495 let kind = key.descr();
1496 let mut returned_async_output_error = false;
1498 if sp.is_desugaring(DesugaringKind::Async) && !returned_async_output_error {
1499 if [sp] != err.span.primary_spans() {
1500 let mut span: MultiSpan = sp.into();
1501 span.push_span_label(
1504 "checked the `Output` of this `async fn`, {}{} {}{}",
1505 if count > 1 { "one of the " } else { "" },
1513 "while checking the return type of the `async fn`",
1519 "checked the `Output` of this `async fn`, {}{} {}{}",
1520 if count > 1 { "one of the " } else { "" },
1526 err.note("while checking the return type of the `async fn`");
1528 returned_async_output_error = true;
1534 if count == 1 { "the " } else { "one of the " },
1546 impl<'tcx> ty::visit::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1547 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1548 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1549 let span = self.tcx.def_span(def_id);
1550 // Avoid cluttering the output when the "found" and error span overlap:
1552 // error[E0308]: mismatched types
1553 // --> $DIR/issue-20862.rs:2:5
1558 // | the found closure
1559 // | expected `()`, found closure
1561 // = note: expected unit type `()`
1562 // found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1563 if !self.ignore_span.overlaps(span) {
1564 self.types.entry(kind).or_default().insert(span);
1567 t.super_visit_with(self)
1571 debug!("note_type_err(diag={:?})", diag);
1573 Variable(ty::error::ExpectedFound<Ty<'a>>),
1574 Fixed(&'static str),
1576 let (expected_found, exp_found, is_simple_error, values) = match values {
1577 None => (None, Mismatch::Fixed("type"), false, None),
1579 let values = self.resolve_vars_if_possible(values);
1580 let (is_simple_error, exp_found) = match values {
1581 ValuePairs::Terms(infer::ExpectedFound {
1582 expected: ty::Term::Ty(expected),
1583 found: ty::Term::Ty(found),
1585 let is_simple_err = expected.is_simple_text() && found.is_simple_text();
1586 OpaqueTypesVisitor::visit_expected_found(self.tcx, expected, found, span)
1591 Mismatch::Variable(infer::ExpectedFound { expected, found }),
1594 ValuePairs::TraitRefs(_) | ValuePairs::PolyTraitRefs(_) => {
1595 (false, Mismatch::Fixed("trait"))
1597 _ => (false, Mismatch::Fixed("type")),
1599 let vals = match self.values_str(values) {
1600 Some((expected, found)) => Some((expected, found)),
1602 // Derived error. Cancel the emitter.
1603 // NOTE(eddyb) this was `.cancel()`, but `diag`
1604 // is borrowed, so we can't fully defuse it.
1605 diag.downgrade_to_delayed_bug();
1609 (vals, exp_found, is_simple_error, Some(values))
1614 // Ignore msg for object safe coercion
1615 // since E0038 message will be printed
1616 TypeError::ObjectUnsafeCoercion(_) => {}
1618 let mut label_or_note = |span: Span, msg: &str| {
1619 if force_label || &[span] == diag.span.primary_spans() {
1620 diag.span_label(span, msg);
1622 diag.span_note(span, msg);
1625 if let Some((sp, msg)) = secondary_span {
1626 if swap_secondary_and_primary {
1627 let terr = if let Some(infer::ValuePairs::Terms(infer::ExpectedFound {
1632 format!("expected this to be `{}`", expected)
1636 label_or_note(sp, &terr);
1637 label_or_note(span, &msg);
1639 label_or_note(span, &terr.to_string());
1640 label_or_note(sp, &msg);
1643 label_or_note(span, &terr.to_string());
1647 if let Some((expected, found)) = expected_found {
1648 let (expected_label, found_label, exp_found) = match exp_found {
1649 Mismatch::Variable(ef) => (
1650 ef.expected.prefix_string(self.tcx),
1651 ef.found.prefix_string(self.tcx),
1654 Mismatch::Fixed(s) => (s.into(), s.into(), None),
1656 match (&terr, expected == found) {
1657 (TypeError::Sorts(values), extra) => {
1658 let sort_string = |ty: Ty<'tcx>| match (extra, ty.kind()) {
1659 (true, ty::Opaque(def_id, _)) => {
1660 let sm = self.tcx.sess.source_map();
1661 let pos = sm.lookup_char_pos(self.tcx.def_span(*def_id).lo());
1663 " (opaque type at <{}:{}:{}>)",
1664 sm.filename_for_diagnostics(&pos.file.name),
1666 pos.col.to_usize() + 1,
1669 (true, _) => format!(" ({})", ty.sort_string(self.tcx)),
1670 (false, _) => "".to_string(),
1672 if !(values.expected.is_simple_text() && values.found.is_simple_text())
1673 || (exp_found.map_or(false, |ef| {
1674 // This happens when the type error is a subset of the expectation,
1675 // like when you have two references but one is `usize` and the other
1676 // is `f32`. In those cases we still want to show the `note`. If the
1677 // value from `ef` is `Infer(_)`, then we ignore it.
1678 if !ef.expected.is_ty_infer() {
1679 ef.expected != values.expected
1680 } else if !ef.found.is_ty_infer() {
1681 ef.found != values.found
1687 diag.note_expected_found_extra(
1692 &sort_string(values.expected),
1693 &sort_string(values.found),
1697 (TypeError::ObjectUnsafeCoercion(_), _) => {
1698 diag.note_unsuccessful_coercion(found, expected);
1702 "note_type_err: exp_found={:?}, expected={:?} found={:?}",
1703 exp_found, expected, found
1705 if !is_simple_error || terr.must_include_note() {
1706 diag.note_expected_found(&expected_label, expected, &found_label, found);
1711 let exp_found = match exp_found {
1712 Mismatch::Variable(exp_found) => Some(exp_found),
1713 Mismatch::Fixed(_) => None,
1715 let exp_found = match terr {
1716 // `terr` has more accurate type information than `exp_found` in match expressions.
1717 ty::error::TypeError::Sorts(terr)
1718 if exp_found.map_or(false, |ef| terr.found == ef.found) =>
1724 debug!("exp_found {:?} terr {:?} cause.code {:?}", exp_found, terr, cause.code());
1725 if let Some(exp_found) = exp_found {
1726 let should_suggest_fixes = if let ObligationCauseCode::Pattern { root_ty, .. } =
1729 // Skip if the root_ty of the pattern is not the same as the expected_ty.
1730 // If these types aren't equal then we've probably peeled off a layer of arrays.
1731 same_type_modulo_infer(self.resolve_vars_if_possible(*root_ty), exp_found.expected)
1736 if should_suggest_fixes {
1737 self.suggest_tuple_pattern(cause, &exp_found, diag);
1738 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1739 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1740 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1744 // In some (most?) cases cause.body_id points to actual body, but in some cases
1745 // it's an actual definition. According to the comments (e.g. in
1746 // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1747 // is relied upon by some other code. This might (or might not) need cleanup.
1748 let body_owner_def_id =
1749 self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1750 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1752 self.check_and_note_conflicting_crates(diag, terr);
1753 self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1755 if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values
1756 && let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind()
1757 && let Some(def_id) = def_id.as_local()
1759 let span = self.tcx.def_span(def_id);
1760 diag.span_note(span, "this closure does not fulfill the lifetime requirements");
1763 // It reads better to have the error origin as the final
1765 self.note_error_origin(diag, cause, exp_found, terr);
1770 fn suggest_tuple_pattern(
1772 cause: &ObligationCause<'tcx>,
1773 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1774 diag: &mut Diagnostic,
1776 // Heavily inspired by `FnCtxt::suggest_compatible_variants`, with
1777 // some modifications due to that being in typeck and this being in infer.
1778 if let ObligationCauseCode::Pattern { .. } = cause.code() {
1779 if let ty::Adt(expected_adt, substs) = exp_found.expected.kind() {
1780 let compatible_variants: Vec<_> = expected_adt
1784 variant.fields.len() == 1 && variant.ctor_kind == hir::def::CtorKind::Fn
1786 .filter_map(|variant| {
1787 let sole_field = &variant.fields[0];
1788 let sole_field_ty = sole_field.ty(self.tcx, substs);
1789 if same_type_modulo_infer(sole_field_ty, exp_found.found) {
1791 with_no_trimmed_paths!(self.tcx.def_path_str(variant.def_id));
1792 // FIXME #56861: DRYer prelude filtering
1793 if let Some(path) = variant_path.strip_prefix("std::prelude::") {
1794 if let Some((_, path)) = path.split_once("::") {
1795 return Some(path.to_string());
1804 match &compatible_variants[..] {
1807 diag.multipart_suggestion_verbose(
1808 &format!("try wrapping the pattern in `{}`", variant),
1810 (cause.span.shrink_to_lo(), format!("{}(", variant)),
1811 (cause.span.shrink_to_hi(), ")".to_string()),
1813 Applicability::MaybeIncorrect,
1817 // More than one matching variant.
1818 diag.multipart_suggestions(
1820 "try wrapping the pattern in a variant of `{}`",
1821 self.tcx.def_path_str(expected_adt.did())
1823 compatible_variants.into_iter().map(|variant| {
1825 (cause.span.shrink_to_lo(), format!("{}(", variant)),
1826 (cause.span.shrink_to_hi(), ")".to_string()),
1829 Applicability::MaybeIncorrect,
1837 pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Binder<'tcx, Ty<'tcx>>> {
1838 if let ty::Opaque(def_id, substs) = ty.kind() {
1839 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
1841 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
1843 let bounds = self.tcx.bound_explicit_item_bounds(*def_id);
1845 for predicate in bounds.transpose_iter().map(|e| e.map_bound(|(p, _)| *p)) {
1846 let predicate = predicate.subst(self.tcx, substs);
1847 let output = predicate
1849 .map_bound(|kind| match kind {
1850 ty::PredicateKind::Projection(projection_predicate)
1851 if projection_predicate.projection_ty.item_def_id == item_def_id =>
1853 projection_predicate.term.ty()
1858 if output.is_some() {
1859 // We don't account for multiple `Future::Output = Ty` constraints.
1867 /// A possible error is to forget to add `.await` when using futures:
1869 /// ```compile_fail,E0308
1870 /// async fn make_u32() -> u32 {
1874 /// fn take_u32(x: u32) {}
1876 /// async fn foo() {
1877 /// let x = make_u32();
1882 /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the
1883 /// expected type. If this is the case, and we are inside of an async body, it suggests adding
1884 /// `.await` to the tail of the expression.
1885 fn suggest_await_on_expect_found(
1887 cause: &ObligationCause<'tcx>,
1889 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1890 diag: &mut Diagnostic,
1893 "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
1894 exp_span, exp_found.expected, exp_found.found,
1897 if let ObligationCauseCode::CompareImplMethodObligation { .. } = cause.code() {
1902 self.get_impl_future_output_ty(exp_found.expected).map(Binder::skip_binder),
1903 self.get_impl_future_output_ty(exp_found.found).map(Binder::skip_binder),
1905 (Some(exp), Some(found)) if same_type_modulo_infer(exp, found) => match cause.code() {
1906 ObligationCauseCode::IfExpression(box IfExpressionCause { then, .. }) => {
1907 diag.multipart_suggestion(
1908 "consider `await`ing on both `Future`s",
1910 (then.shrink_to_hi(), ".await".to_string()),
1911 (exp_span.shrink_to_hi(), ".await".to_string()),
1913 Applicability::MaybeIncorrect,
1916 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1920 if let [.., arm_span] = &prior_arms[..] {
1921 diag.multipart_suggestion(
1922 "consider `await`ing on both `Future`s",
1924 (arm_span.shrink_to_hi(), ".await".to_string()),
1925 (exp_span.shrink_to_hi(), ".await".to_string()),
1927 Applicability::MaybeIncorrect,
1930 diag.help("consider `await`ing on both `Future`s");
1934 diag.help("consider `await`ing on both `Future`s");
1937 (_, Some(ty)) if same_type_modulo_infer(exp_found.expected, ty) => {
1938 diag.span_suggestion_verbose(
1939 exp_span.shrink_to_hi(),
1940 "consider `await`ing on the `Future`",
1942 Applicability::MaybeIncorrect,
1945 (Some(ty), _) if same_type_modulo_infer(ty, exp_found.found) => match cause.code() {
1946 ObligationCauseCode::Pattern { span: Some(span), .. }
1947 | ObligationCauseCode::IfExpression(box IfExpressionCause { then: span, .. }) => {
1948 diag.span_suggestion_verbose(
1949 span.shrink_to_hi(),
1950 "consider `await`ing on the `Future`",
1952 Applicability::MaybeIncorrect,
1955 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1959 diag.multipart_suggestion_verbose(
1960 "consider `await`ing on the `Future`",
1963 .map(|arm| (arm.shrink_to_hi(), ".await".to_string()))
1965 Applicability::MaybeIncorrect,
1974 fn suggest_accessing_field_where_appropriate(
1976 cause: &ObligationCause<'tcx>,
1977 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1978 diag: &mut Diagnostic,
1981 "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})",
1984 if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() {
1985 if expected_def.is_enum() {
1989 if let Some((name, ty)) = expected_def
1993 .filter(|field| field.vis.is_accessible_from(field.did, self.tcx))
1994 .map(|field| (field.name, field.ty(self.tcx, expected_substs)))
1995 .find(|(_, ty)| same_type_modulo_infer(*ty, exp_found.found))
1997 if let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() {
1998 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1999 let suggestion = if expected_def.is_struct() {
2000 format!("{}.{}", snippet, name)
2001 } else if expected_def.is_union() {
2002 format!("unsafe {{ {}.{} }}", snippet, name)
2006 diag.span_suggestion(
2009 "you might have meant to use field `{}` whose type is `{}`",
2013 Applicability::MaybeIncorrect,
2021 /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
2023 fn suggest_as_ref_where_appropriate(
2026 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
2027 diag: &mut Diagnostic,
2029 if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
2030 (exp_found.expected.kind(), exp_found.found.kind())
2032 if let ty::Adt(found_def, found_substs) = *found_ty.kind() {
2033 let path_str = format!("{:?}", exp_def);
2034 if exp_def == &found_def {
2035 let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
2037 let result_msg = "you can convert from `&Result<T, E>` to \
2038 `Result<&T, &E>` using `.as_ref()`";
2039 let have_as_ref = &[
2040 ("std::option::Option", opt_msg),
2041 ("core::option::Option", opt_msg),
2042 ("std::result::Result", result_msg),
2043 ("core::result::Result", result_msg),
2045 if let Some(msg) = have_as_ref
2047 .find_map(|(path, msg)| (&path_str == path).then_some(msg))
2049 let mut show_suggestion = true;
2050 for (exp_ty, found_ty) in
2051 iter::zip(exp_substs.types(), found_substs.types())
2053 match *exp_ty.kind() {
2054 ty::Ref(_, exp_ty, _) => {
2055 match (exp_ty.kind(), found_ty.kind()) {
2059 | (ty::Infer(_), _) => {}
2060 _ if same_type_modulo_infer(exp_ty, found_ty) => {}
2061 _ => show_suggestion = false,
2064 ty::Param(_) | ty::Infer(_) => {}
2065 _ => show_suggestion = false,
2068 if let (Ok(snippet), true) =
2069 (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion)
2071 diag.span_suggestion(
2074 format!("{}.as_ref()", snippet),
2075 Applicability::MachineApplicable,
2084 pub fn report_and_explain_type_error(
2086 trace: TypeTrace<'tcx>,
2087 terr: &TypeError<'tcx>,
2088 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2089 use crate::traits::ObligationCauseCode::MatchExpressionArm;
2091 debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
2093 let span = trace.cause.span();
2094 let failure_code = trace.cause.as_failure_code(terr);
2095 let mut diag = match failure_code {
2096 FailureCode::Error0038(did) => {
2097 let violations = self.tcx.object_safety_violations(did);
2098 report_object_safety_error(self.tcx, span, did, violations)
2100 FailureCode::Error0317(failure_str) => {
2101 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
2103 FailureCode::Error0580(failure_str) => {
2104 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
2106 FailureCode::Error0308(failure_str) => {
2107 let mut err = struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str);
2108 if let Some((expected, found)) = trace.values.ty() {
2109 match (expected.kind(), found.kind()) {
2110 (ty::Tuple(_), ty::Tuple(_)) => {}
2111 // If a tuple of length one was expected and the found expression has
2112 // parentheses around it, perhaps the user meant to write `(expr,)` to
2113 // build a tuple (issue #86100)
2114 (ty::Tuple(fields), _) => {
2115 self.emit_tuple_wrap_err(&mut err, span, found, fields)
2117 // If a character was expected and the found expression is a string literal
2118 // containing a single character, perhaps the user meant to write `'c'` to
2119 // specify a character literal (issue #92479)
2120 (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
2121 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2122 && let Some(code) = code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
2123 && code.chars().count() == 1
2125 err.span_suggestion(
2127 "if you meant to write a `char` literal, use single quotes",
2128 format!("'{}'", code),
2129 Applicability::MachineApplicable,
2133 // If a string was expected and the found expression is a character literal,
2134 // perhaps the user meant to write `"s"` to specify a string literal.
2135 (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
2136 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
2138 code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
2140 err.span_suggestion(
2142 "if you meant to write a `str` literal, use double quotes",
2143 format!("\"{}\"", code),
2144 Applicability::MachineApplicable,
2152 let code = trace.cause.code();
2153 if let &MatchExpressionArm(box MatchExpressionArmCause { source, .. }) = code
2154 && let hir::MatchSource::TryDesugar = source
2155 && let Some((expected_ty, found_ty)) = self.values_str(trace.values)
2158 "`?` operator cannot convert from `{}` to `{}`",
2160 expected_ty.content(),
2165 FailureCode::Error0644(failure_str) => {
2166 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
2169 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false, false);
2173 fn emit_tuple_wrap_err(
2175 err: &mut Diagnostic,
2178 expected_fields: &List<Ty<'tcx>>,
2180 let [expected_tup_elem] = expected_fields[..] else { return };
2182 if !same_type_modulo_infer(expected_tup_elem, found) {
2186 let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span)
2189 let msg = "use a trailing comma to create a tuple with one element";
2190 if code.starts_with('(') && code.ends_with(')') {
2191 let before_close = span.hi() - BytePos::from_u32(1);
2192 err.span_suggestion(
2193 span.with_hi(before_close).shrink_to_hi(),
2196 Applicability::MachineApplicable,
2199 err.multipart_suggestion(
2201 vec![(span.shrink_to_lo(), "(".into()), (span.shrink_to_hi(), ",)".into())],
2202 Applicability::MachineApplicable,
2209 values: ValuePairs<'tcx>,
2210 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2212 infer::Regions(exp_found) => self.expected_found_str(exp_found),
2213 infer::Terms(exp_found) => self.expected_found_str_term(exp_found),
2214 infer::TraitRefs(exp_found) => {
2215 let pretty_exp_found = ty::error::ExpectedFound {
2216 expected: exp_found.expected.print_only_trait_path(),
2217 found: exp_found.found.print_only_trait_path(),
2219 match self.expected_found_str(pretty_exp_found) {
2220 Some((expected, found)) if expected == found => {
2221 self.expected_found_str(exp_found)
2226 infer::PolyTraitRefs(exp_found) => {
2227 let pretty_exp_found = ty::error::ExpectedFound {
2228 expected: exp_found.expected.print_only_trait_path(),
2229 found: exp_found.found.print_only_trait_path(),
2231 match self.expected_found_str(pretty_exp_found) {
2232 Some((expected, found)) if expected == found => {
2233 self.expected_found_str(exp_found)
2241 fn expected_found_str_term(
2243 exp_found: ty::error::ExpectedFound<ty::Term<'tcx>>,
2244 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2245 let exp_found = self.resolve_vars_if_possible(exp_found);
2246 if exp_found.references_error() {
2250 Some(match (exp_found.expected, exp_found.found) {
2251 (ty::Term::Ty(expected), ty::Term::Ty(found)) => self.cmp(expected, found),
2252 (expected, found) => (
2253 DiagnosticStyledString::highlighted(expected.to_string()),
2254 DiagnosticStyledString::highlighted(found.to_string()),
2259 /// Returns a string of the form "expected `{}`, found `{}`".
2260 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
2262 exp_found: ty::error::ExpectedFound<T>,
2263 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2264 let exp_found = self.resolve_vars_if_possible(exp_found);
2265 if exp_found.references_error() {
2270 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2271 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2275 pub fn report_generic_bound_failure(
2277 generic_param_scope: LocalDefId,
2279 origin: Option<SubregionOrigin<'tcx>>,
2280 bound_kind: GenericKind<'tcx>,
2283 self.construct_generic_bound_failure(generic_param_scope, span, origin, bound_kind, sub)
2287 pub fn construct_generic_bound_failure(
2289 generic_param_scope: LocalDefId,
2291 origin: Option<SubregionOrigin<'tcx>>,
2292 bound_kind: GenericKind<'tcx>,
2294 ) -> DiagnosticBuilder<'a, ErrorGuaranteed> {
2295 // Attempt to obtain the span of the parameter so we can
2296 // suggest adding an explicit lifetime bound to it.
2297 let generics = self.tcx.generics_of(generic_param_scope);
2298 // type_param_span is (span, has_bounds)
2299 let type_param_span = match bound_kind {
2300 GenericKind::Param(ref param) => {
2301 // Account for the case where `param` corresponds to `Self`,
2302 // which doesn't have the expected type argument.
2303 if !(generics.has_self && param.index == 0) {
2304 let type_param = generics.type_param(param, self.tcx);
2305 type_param.def_id.as_local().map(|def_id| {
2306 // Get the `hir::Param` to verify whether it already has any bounds.
2307 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
2308 // instead we suggest `T: 'a + 'b` in that case.
2309 let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
2310 let ast_generics = self.tcx.hir().get_generics(hir_id.owner);
2312 ast_generics.and_then(|g| g.bounds_span_for_suggestions(def_id));
2313 // `sp` only covers `T`, change it so that it covers
2314 // `T:` when appropriate
2315 if let Some(span) = bounds {
2318 let sp = self.tcx.def_span(def_id);
2319 (sp.shrink_to_hi(), false)
2330 let mut possible = (b'a'..=b'z').map(|c| format!("'{}", c as char));
2332 iter::successors(Some(generics), |g| g.parent.map(|p| self.tcx.generics_of(p)))
2333 .flat_map(|g| &g.params)
2334 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2335 .map(|p| p.name.as_str())
2336 .collect::<Vec<_>>();
2338 .find(|candidate| !lts_names.contains(&&candidate[..]))
2339 .unwrap_or("'lt".to_string())
2342 let add_lt_sugg = generics
2345 .and_then(|param| param.def_id.as_local())
2346 .map(|def_id| (self.tcx.def_span(def_id).shrink_to_lo(), format!("{}, ", new_lt)));
2348 let labeled_user_string = match bound_kind {
2349 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
2350 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
2353 if let Some(SubregionOrigin::CompareImplMethodObligation {
2359 return self.report_extra_impl_obligation(
2363 &format!("`{}: {}`", bound_kind, sub),
2367 fn binding_suggestion<'tcx, S: fmt::Display>(
2368 err: &mut Diagnostic,
2369 type_param_span: Option<(Span, bool)>,
2370 bound_kind: GenericKind<'tcx>,
2373 let msg = "consider adding an explicit lifetime bound";
2374 if let Some((sp, has_lifetimes)) = type_param_span {
2376 if has_lifetimes { format!(" + {}", sub) } else { format!(": {}", sub) };
2377 err.span_suggestion_verbose(
2379 &format!("{}...", msg),
2381 Applicability::MaybeIncorrect, // Issue #41966
2384 let consider = format!("{} `{}: {}`...", msg, bound_kind, sub,);
2385 err.help(&consider);
2389 let new_binding_suggestion =
2390 |err: &mut Diagnostic, type_param_span: Option<(Span, bool)>| {
2391 let msg = "consider introducing an explicit lifetime bound";
2392 if let Some((sp, has_lifetimes)) = type_param_span {
2393 let suggestion = if has_lifetimes {
2394 format!(" + {}", new_lt)
2396 format!(": {}", new_lt)
2399 vec![(sp, suggestion), (span.shrink_to_hi(), format!(" + {}", new_lt))];
2400 if let Some(lt) = add_lt_sugg {
2402 sugg.rotate_right(1);
2404 // `MaybeIncorrect` due to issue #41966.
2405 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2410 enum SubOrigin<'hir> {
2411 GAT(&'hir hir::Generics<'hir>),
2412 Impl(&'hir hir::Generics<'hir>),
2413 Trait(&'hir hir::Generics<'hir>),
2414 Fn(&'hir hir::Generics<'hir>),
2417 let sub_origin = 'origin: {
2419 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
2420 let node = self.tcx.hir().get_if_local(def_id).unwrap();
2422 Node::GenericParam(param) => {
2423 for h in self.tcx.hir().parent_iter(param.hir_id) {
2424 break 'origin match h.1 {
2425 Node::ImplItem(hir::ImplItem {
2426 kind: hir::ImplItemKind::TyAlias(..),
2429 }) => SubOrigin::GAT(generics),
2430 Node::ImplItem(hir::ImplItem {
2431 kind: hir::ImplItemKind::Fn(..),
2434 }) => SubOrigin::Fn(generics),
2435 Node::TraitItem(hir::TraitItem {
2436 kind: hir::TraitItemKind::Type(..),
2439 }) => SubOrigin::GAT(generics),
2440 Node::TraitItem(hir::TraitItem {
2441 kind: hir::TraitItemKind::Fn(..),
2444 }) => SubOrigin::Fn(generics),
2445 Node::Item(hir::Item {
2446 kind: hir::ItemKind::Trait(_, _, generics, _, _),
2448 }) => SubOrigin::Trait(generics),
2449 Node::Item(hir::Item {
2450 kind: hir::ItemKind::Impl(hir::Impl { generics, .. }),
2452 }) => SubOrigin::Impl(generics),
2453 Node::Item(hir::Item {
2454 kind: hir::ItemKind::Fn(_, generics, _),
2456 }) => SubOrigin::Fn(generics),
2468 debug!(?sub_origin);
2470 let mut err = match (*sub, sub_origin) {
2471 // In the case of GATs, we have to be careful. If we a type parameter `T` on an impl,
2472 // but a lifetime `'a` on an associated type, then we might need to suggest adding
2473 // `where T: 'a`. Importantly, this is on the GAT span, not on the `T` declaration.
2474 (ty::ReEarlyBound(ty::EarlyBoundRegion { name: _, .. }), SubOrigin::GAT(generics)) => {
2475 // Does the required lifetime have a nice name we can print?
2476 let mut err = struct_span_err!(
2480 "{} may not live long enough",
2483 let pred = format!("{}: {}", bound_kind, sub);
2484 let suggestion = format!("{} {}", generics.add_where_or_trailing_comma(), pred,);
2485 err.span_suggestion(
2486 generics.tail_span_for_predicate_suggestion(),
2487 "consider adding a where clause",
2489 Applicability::MaybeIncorrect,
2494 ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
2495 | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }),
2497 ) if name != kw::UnderscoreLifetime => {
2498 // Does the required lifetime have a nice name we can print?
2499 let mut err = struct_span_err!(
2503 "{} may not live long enough",
2506 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
2507 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
2508 // uses `Debug` output, so we handle it specially here so that suggestions are
2510 binding_suggestion(&mut err, type_param_span, bound_kind, name);
2514 (ty::ReStatic, _) => {
2515 // Does the required lifetime have a nice name we can print?
2516 let mut err = struct_span_err!(
2520 "{} may not live long enough",
2523 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
2528 // If not, be less specific.
2529 let mut err = struct_span_err!(
2533 "{} may not live long enough",
2536 note_and_explain_region(
2539 &format!("{} must be valid for ", labeled_user_string),
2544 if let Some(infer::RelateParamBound(_, t, _)) = origin {
2545 let return_impl_trait =
2546 self.tcx.return_type_impl_trait(generic_param_scope).is_some();
2547 let t = self.resolve_vars_if_possible(t);
2550 // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
2552 // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
2553 ty::Closure(_, _substs) | ty::Opaque(_, _substs) if return_impl_trait => {
2554 new_binding_suggestion(&mut err, type_param_span);
2557 binding_suggestion(&mut err, type_param_span, bound_kind, new_lt);
2565 if let Some(origin) = origin {
2566 self.note_region_origin(&mut err, &origin);
2571 fn report_sub_sup_conflict(
2573 var_origin: RegionVariableOrigin,
2574 sub_origin: SubregionOrigin<'tcx>,
2575 sub_region: Region<'tcx>,
2576 sup_origin: SubregionOrigin<'tcx>,
2577 sup_region: Region<'tcx>,
2579 let mut err = self.report_inference_failure(var_origin);
2581 note_and_explain_region(
2584 "first, the lifetime cannot outlive ",
2590 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
2591 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
2592 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
2593 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
2594 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
2596 if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
2597 (&sup_origin, &sub_origin)
2599 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
2600 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
2601 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
2602 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
2604 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
2605 (self.values_str(sup_trace.values), self.values_str(sub_trace.values))
2607 if sub_expected == sup_expected && sub_found == sup_found {
2608 note_and_explain_region(
2611 "...but the lifetime must also be valid for ",
2617 sup_trace.cause.span,
2618 &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
2621 err.note_expected_found(&"", sup_expected, &"", sup_found);
2628 self.note_region_origin(&mut err, &sup_origin);
2630 note_and_explain_region(
2633 "but, the lifetime must be valid for ",
2639 self.note_region_origin(&mut err, &sub_origin);
2643 /// Determine whether an error associated with the given span and definition
2644 /// should be treated as being caused by the implicit `From` conversion
2645 /// within `?` desugaring.
2646 pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2647 span.is_desugaring(DesugaringKind::QuestionMark)
2648 && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2652 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2653 fn report_inference_failure(
2655 var_origin: RegionVariableOrigin,
2656 ) -> DiagnosticBuilder<'tcx, ErrorGuaranteed> {
2657 let br_string = |br: ty::BoundRegionKind| {
2658 let mut s = match br {
2659 ty::BrNamed(_, name) => name.to_string(),
2667 let var_description = match var_origin {
2668 infer::MiscVariable(_) => String::new(),
2669 infer::PatternRegion(_) => " for pattern".to_string(),
2670 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2671 infer::Autoref(_) => " for autoref".to_string(),
2672 infer::Coercion(_) => " for automatic coercion".to_string(),
2673 infer::LateBoundRegion(_, br, infer::FnCall) => {
2674 format!(" for lifetime parameter {}in function call", br_string(br))
2676 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2677 format!(" for lifetime parameter {}in generic type", br_string(br))
2679 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2680 " for lifetime parameter {}in trait containing associated type `{}`",
2682 self.tcx.associated_item(def_id).name
2684 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2685 infer::UpvarRegion(ref upvar_id, _) => {
2686 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2687 format!(" for capture of `{}` by closure", var_name)
2689 infer::Nll(..) => bug!("NLL variable found in lexical phase"),
2696 "cannot infer an appropriate lifetime{} due to conflicting requirements",
2702 pub enum FailureCode {
2704 Error0317(&'static str),
2705 Error0580(&'static str),
2706 Error0308(&'static str),
2707 Error0644(&'static str),
2710 pub trait ObligationCauseExt<'tcx> {
2711 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode;
2712 fn as_requirement_str(&self) -> &'static str;
2715 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2716 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
2717 use self::FailureCode::*;
2718 use crate::traits::ObligationCauseCode::*;
2720 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
2721 CompareImplTypeObligation { .. } => Error0308("type not compatible with trait"),
2722 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
2723 Error0308(match source {
2724 hir::MatchSource::TryDesugar => "`?` operator has incompatible types",
2725 _ => "`match` arms have incompatible types",
2728 IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
2729 IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
2730 LetElse => Error0308("`else` clause of `let...else` does not diverge"),
2731 MainFunctionType => Error0580("`main` function has wrong type"),
2732 StartFunctionType => Error0308("`#[start]` function has wrong type"),
2733 IntrinsicType => Error0308("intrinsic has wrong type"),
2734 MethodReceiver => Error0308("mismatched `self` parameter type"),
2736 // In the case where we have no more specific thing to
2737 // say, also take a look at the error code, maybe we can
2740 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
2741 Error0644("closure/generator type that references itself")
2743 TypeError::IntrinsicCast => {
2744 Error0308("cannot coerce intrinsics to function pointers")
2746 TypeError::ObjectUnsafeCoercion(did) => Error0038(*did),
2747 _ => Error0308("mismatched types"),
2752 fn as_requirement_str(&self) -> &'static str {
2753 use crate::traits::ObligationCauseCode::*;
2755 CompareImplMethodObligation { .. } => "method type is compatible with trait",
2756 CompareImplTypeObligation { .. } => "associated type is compatible with trait",
2757 ExprAssignable => "expression is assignable",
2758 IfExpression { .. } => "`if` and `else` have incompatible types",
2759 IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
2760 MainFunctionType => "`main` function has the correct type",
2761 StartFunctionType => "`#[start]` function has the correct type",
2762 IntrinsicType => "intrinsic has the correct type",
2763 MethodReceiver => "method receiver has the correct type",
2764 _ => "types are compatible",
2769 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2770 /// extra information about each type, but we only care about the category.
2771 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2772 pub enum TyCategory {
2775 Generator(hir::GeneratorKind),
2780 fn descr(&self) -> &'static str {
2782 Self::Closure => "closure",
2783 Self::Opaque => "opaque type",
2784 Self::Generator(gk) => gk.descr(),
2785 Self::Foreign => "foreign type",
2789 pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2791 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2792 ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
2793 ty::Generator(def_id, ..) => {
2794 Some((Self::Generator(tcx.generator_kind(def_id).unwrap()), def_id))
2796 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),