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};
62 use rustc_errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString};
64 use rustc_hir::def_id::DefId;
65 use rustc_hir::lang_items::LangItem;
66 use rustc_hir::{Item, ItemKind, Node};
67 use rustc_middle::dep_graph::DepContext;
68 use rustc_middle::ty::{
71 subst::{GenericArgKind, Subst, SubstsRef},
72 Binder, Region, Ty, TyCtxt, TypeFoldable,
74 use rustc_span::{sym, BytePos, DesugaringKind, MultiSpan, Pos, Span};
75 use rustc_target::spec::abi;
76 use std::ops::ControlFlow;
77 use std::{cmp, fmt, iter};
82 pub use need_type_info::TypeAnnotationNeeded;
84 pub mod nice_region_error;
86 pub(super) fn note_and_explain_region<'tcx>(
88 err: &mut DiagnosticBuilder<'_>,
90 region: ty::Region<'tcx>,
92 alt_span: Option<Span>,
94 let (description, span) = match *region {
95 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
96 msg_span_from_free_region(tcx, region, alt_span)
99 ty::ReEmpty(ty::UniverseIndex::ROOT) => ("the empty lifetime".to_owned(), alt_span),
101 // uh oh, hope no user ever sees THIS
102 ty::ReEmpty(ui) => (format!("the empty lifetime in universe {:?}", ui), alt_span),
104 ty::RePlaceholder(_) => return,
106 // FIXME(#13998) RePlaceholder should probably print like
107 // ReFree rather than dumping Debug output on the user.
109 // We shouldn't really be having unification failures with ReVar
110 // and ReLateBound though.
111 ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
112 (format!("lifetime {:?}", region), alt_span)
116 emit_msg_span(err, prefix, description, span, suffix);
119 fn explain_free_region<'tcx>(
121 err: &mut DiagnosticBuilder<'_>,
123 region: ty::Region<'tcx>,
126 let (description, span) = msg_span_from_free_region(tcx, region, None);
128 label_msg_span(err, prefix, description, span, suffix);
131 fn msg_span_from_free_region<'tcx>(
133 region: ty::Region<'tcx>,
134 alt_span: Option<Span>,
135 ) -> (String, Option<Span>) {
137 ty::ReEarlyBound(_) | ty::ReFree(_) => {
138 let (msg, span) = msg_span_from_early_bound_and_free_regions(tcx, region);
141 ty::ReStatic => ("the static lifetime".to_owned(), alt_span),
142 ty::ReEmpty(ty::UniverseIndex::ROOT) => ("an empty lifetime".to_owned(), alt_span),
143 ty::ReEmpty(ui) => (format!("an empty lifetime in universe {:?}", ui), alt_span),
144 _ => bug!("{:?}", region),
148 fn msg_span_from_early_bound_and_free_regions<'tcx>(
150 region: ty::Region<'tcx>,
151 ) -> (String, Span) {
152 let sm = tcx.sess.source_map();
154 let scope = region.free_region_binding_scope(tcx).expect_local();
156 ty::ReEarlyBound(ref br) => {
157 let mut sp = sm.guess_head_span(tcx.def_span(scope));
159 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(br.name))
163 (format!("the lifetime `{}` as defined here", br.name), sp)
165 ty::ReFree(ty::FreeRegion {
166 bound_region: ty::BoundRegionKind::BrNamed(_, name), ..
168 let mut sp = sm.guess_head_span(tcx.def_span(scope));
170 tcx.hir().get_generics(scope).and_then(|generics| generics.get_named(name))
174 (format!("the lifetime `{}` as defined here", name), sp)
176 ty::ReFree(ref fr) => match fr.bound_region {
178 if let Some((ty, _)) = find_anon_type(tcx, region, &fr.bound_region) {
179 ("the anonymous lifetime defined here".to_string(), ty.span)
182 format!("the anonymous lifetime #{} defined here", idx + 1),
188 format!("the lifetime `{}` as defined here", region),
189 sm.guess_head_span(tcx.def_span(scope)),
197 err: &mut DiagnosticBuilder<'_>,
203 let message = format!("{}{}{}", prefix, description, suffix);
205 if let Some(span) = span {
206 err.span_note(span, &message);
213 err: &mut DiagnosticBuilder<'_>,
219 let message = format!("{}{}{}", prefix, description, suffix);
221 if let Some(span) = span {
222 err.span_label(span, &message);
228 pub fn unexpected_hidden_region_diagnostic<'tcx>(
232 hidden_region: ty::Region<'tcx>,
233 ) -> DiagnosticBuilder<'tcx> {
234 let mut err = struct_span_err!(
238 "hidden type for `impl Trait` captures lifetime that does not appear in bounds",
241 // Explain the region we are capturing.
242 match hidden_region {
243 ty::ReEmpty(ty::UniverseIndex::ROOT) => {
244 // All lifetimes shorter than the function body are `empty` in
245 // lexical region resolution. The default explanation of "an empty
246 // lifetime" isn't really accurate here.
247 let message = format!(
248 "hidden type `{}` captures lifetime smaller than the function body",
251 err.span_note(span, &message);
253 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty(_) => {
254 // Assuming regionck succeeded (*), we ought to always be
255 // capturing *some* region from the fn header, and hence it
256 // ought to be free. So under normal circumstances, we will go
257 // down this path which gives a decent human readable
260 // (*) if not, the `tainted_by_errors` field would be set to
261 // `Some(ErrorReported)` in any case, so we wouldn't be here at all.
265 &format!("hidden type `{}` captures ", hidden_ty),
269 if let Some(reg_info) = tcx.is_suitable_region(hidden_region) {
270 let fn_returns = tcx.return_type_impl_or_dyn_traits(reg_info.def_id);
271 nice_region_error::suggest_new_region_bound(
275 hidden_region.to_string(),
277 format!("captures `{}`", hidden_region),
283 // Ugh. This is a painful case: the hidden region is not one
284 // that we can easily summarize or explain. This can happen
286 // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
289 // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
290 // if condition() { a } else { b }
294 // Here the captured lifetime is the intersection of `'a` and
295 // `'b`, which we can't quite express.
297 // We can at least report a really cryptic error for now.
298 note_and_explain_region(
301 &format!("hidden type `{}` captures ", hidden_ty),
312 /// Structurally compares two types, modulo any inference variables.
314 /// Returns `true` if two types are equal, or if one type is an inference variable compatible
315 /// with the other type. A TyVar inference type is compatible with any type, and an IntVar or
316 /// FloatVar inference type are compatible with themselves or their concrete types (Int and
317 /// Float types, respectively). When comparing two ADTs, these rules apply recursively.
318 pub fn same_type_modulo_infer<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
319 match (&a.kind(), &b.kind()) {
320 (&ty::Adt(did_a, substs_a), &ty::Adt(did_b, substs_b)) => {
325 substs_a.types().zip(substs_b.types()).all(|(a, b)| same_type_modulo_infer(a, b))
327 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
328 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)))
329 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
331 &ty::Infer(ty::InferTy::FloatVar(_)),
332 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
334 | (&ty::Infer(ty::InferTy::TyVar(_)), _)
335 | (_, &ty::Infer(ty::InferTy::TyVar(_))) => true,
340 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
341 pub fn report_region_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>) {
342 debug!("report_region_errors(): {} errors to start", errors.len());
344 // try to pre-process the errors, which will group some of them
345 // together into a `ProcessedErrors` group:
346 let errors = self.process_errors(errors);
348 debug!("report_region_errors: {} errors after preprocessing", errors.len());
350 for error in errors {
351 debug!("report_region_errors: error = {:?}", error);
353 if !self.try_report_nice_region_error(&error) {
354 match error.clone() {
355 // These errors could indicate all manner of different
356 // problems with many different solutions. Rather
357 // than generate a "one size fits all" error, what we
358 // attempt to do is go through a number of specific
359 // scenarios and try to find the best way to present
360 // the error. If all of these fails, we fall back to a rather
361 // general bit of code that displays the error information
362 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
363 if sub.is_placeholder() || sup.is_placeholder() {
364 self.report_placeholder_failure(origin, sub, sup).emit();
366 self.report_concrete_failure(origin, sub, sup).emit();
370 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
371 self.report_generic_bound_failure(
379 RegionResolutionError::SubSupConflict(
388 if sub_r.is_placeholder() {
389 self.report_placeholder_failure(sub_origin, sub_r, sup_r).emit();
390 } else if sup_r.is_placeholder() {
391 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
393 self.report_sub_sup_conflict(
394 var_origin, sub_origin, sub_r, sup_origin, sup_r,
399 RegionResolutionError::UpperBoundUniverseConflict(
406 assert!(sup_r.is_placeholder());
408 // Make a dummy value for the "sub region" --
409 // this is the initial value of the
410 // placeholder. In practice, we expect more
411 // tailored errors that don't really use this
413 let sub_r = self.tcx.mk_region(ty::ReEmpty(var_universe));
415 self.report_placeholder_failure(sup_origin, sub_r, sup_r).emit();
422 // This method goes through all the errors and try to group certain types
423 // of error together, for the purpose of suggesting explicit lifetime
424 // parameters to the user. This is done so that we can have a more
425 // complete view of what lifetimes should be the same.
426 // If the return value is an empty vector, it means that processing
427 // failed (so the return value of this method should not be used).
429 // The method also attempts to weed out messages that seem like
430 // duplicates that will be unhelpful to the end-user. But
431 // obviously it never weeds out ALL errors.
434 errors: &[RegionResolutionError<'tcx>],
435 ) -> Vec<RegionResolutionError<'tcx>> {
436 debug!("process_errors()");
438 // We want to avoid reporting generic-bound failures if we can
439 // avoid it: these have a very high rate of being unhelpful in
440 // practice. This is because they are basically secondary
441 // checks that test the state of the region graph after the
442 // rest of inference is done, and the other kinds of errors
443 // indicate that the region constraint graph is internally
444 // inconsistent, so these test results are likely to be
447 // Therefore, we filter them out of the list unless they are
448 // the only thing in the list.
450 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
451 RegionResolutionError::GenericBoundFailure(..) => true,
452 RegionResolutionError::ConcreteFailure(..)
453 | RegionResolutionError::SubSupConflict(..)
454 | RegionResolutionError::UpperBoundUniverseConflict(..) => false,
457 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
460 errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
463 // sort the errors by span, for better error message stability.
464 errors.sort_by_key(|u| match *u {
465 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
466 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
467 RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _, _) => rvo.span(),
468 RegionResolutionError::UpperBoundUniverseConflict(_, ref rvo, _, _, _) => rvo.span(),
473 /// Adds a note if the types come from similarly named crates
474 fn check_and_note_conflicting_crates(
476 err: &mut DiagnosticBuilder<'_>,
477 terr: &TypeError<'tcx>,
479 use hir::def_id::CrateNum;
480 use rustc_hir::definitions::DisambiguatedDefPathData;
481 use ty::print::Printer;
482 use ty::subst::GenericArg;
484 struct AbsolutePathPrinter<'tcx> {
488 struct NonTrivialPath;
490 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
491 type Error = NonTrivialPath;
493 type Path = Vec<String>;
496 type DynExistential = !;
499 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
503 fn print_region(self, _region: ty::Region<'_>) -> Result<Self::Region, Self::Error> {
507 fn print_type(self, _ty: Ty<'tcx>) -> Result<Self::Type, Self::Error> {
511 fn print_dyn_existential(
513 _predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
514 ) -> Result<Self::DynExistential, Self::Error> {
518 fn print_const(self, _ct: &'tcx ty::Const<'tcx>) -> Result<Self::Const, Self::Error> {
522 fn path_crate(self, cnum: CrateNum) -> Result<Self::Path, Self::Error> {
523 Ok(vec![self.tcx.crate_name(cnum).to_string()])
528 _trait_ref: Option<ty::TraitRef<'tcx>>,
529 ) -> Result<Self::Path, Self::Error> {
535 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
536 _disambiguated_data: &DisambiguatedDefPathData,
538 _trait_ref: Option<ty::TraitRef<'tcx>>,
539 ) -> Result<Self::Path, Self::Error> {
544 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
545 disambiguated_data: &DisambiguatedDefPathData,
546 ) -> Result<Self::Path, Self::Error> {
547 let mut path = print_prefix(self)?;
548 path.push(disambiguated_data.to_string());
551 fn path_generic_args(
553 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
554 _args: &[GenericArg<'tcx>],
555 ) -> Result<Self::Path, Self::Error> {
560 let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
561 // Only external crates, if either is from a local
562 // module we could have false positives
563 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
565 |def_id| AbsolutePathPrinter { tcx: self.tcx }.print_def_path(def_id, &[]);
567 // We compare strings because DefPath can be different
568 // for imported and non-imported crates
569 let same_path = || -> Result<_, NonTrivialPath> {
570 Ok(self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2)
571 || abs_path(did1)? == abs_path(did2)?)
573 if same_path().unwrap_or(false) {
574 let crate_name = self.tcx.crate_name(did1.krate);
576 "perhaps two different versions of crate `{}` are being used?",
583 TypeError::Sorts(ref exp_found) => {
584 // if they are both "path types", there's a chance of ambiguity
585 // due to different versions of the same crate
586 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _)) =
587 (exp_found.expected.kind(), exp_found.found.kind())
589 report_path_match(err, exp_adt.did, found_adt.did);
592 TypeError::Traits(ref exp_found) => {
593 report_path_match(err, exp_found.expected, exp_found.found);
595 _ => (), // FIXME(#22750) handle traits and stuff
599 fn note_error_origin(
601 err: &mut DiagnosticBuilder<'tcx>,
602 cause: &ObligationCause<'tcx>,
603 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
604 terr: &TypeError<'tcx>,
606 match *cause.code() {
607 ObligationCauseCode::Pattern { origin_expr: true, span: Some(span), root_ty } => {
608 let ty = self.resolve_vars_if_possible(root_ty);
609 if ty.is_suggestable() {
610 // don't show type `_`
611 err.span_label(span, format!("this expression has type `{}`", ty));
613 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found {
614 if ty.is_box() && ty.boxed_ty() == found {
615 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
618 "consider dereferencing the boxed value",
619 format!("*{}", snippet),
620 Applicability::MachineApplicable,
626 ObligationCauseCode::Pattern { origin_expr: false, span: Some(span), .. } => {
627 err.span_label(span, "expected due to this");
629 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
635 opt_suggest_box_span,
640 hir::MatchSource::TryDesugar => {
641 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
642 let scrut_expr = self.tcx.hir().expect_expr(scrut_hir_id);
643 let scrut_ty = if let hir::ExprKind::Call(_, args) = &scrut_expr.kind {
644 let arg_expr = args.first().expect("try desugaring call w/out arg");
645 self.in_progress_typeck_results.and_then(|typeck_results| {
646 typeck_results.borrow().expr_ty_opt(arg_expr)
649 bug!("try desugaring w/out call expr as scrutinee");
653 Some(ty) if expected == ty => {
654 let source_map = self.tcx.sess.source_map();
656 source_map.end_point(cause.span),
657 "try removing this `?`",
659 Applicability::MachineApplicable,
667 // `last_ty` can be `!`, `expected` will have better info when present.
668 let t = self.resolve_vars_if_possible(match exp_found {
669 Some(ty::error::ExpectedFound { expected, .. }) => expected,
672 let source_map = self.tcx.sess.source_map();
673 let mut any_multiline_arm = source_map.is_multiline(arm_span);
674 if prior_arms.len() <= 4 {
675 for sp in prior_arms {
676 any_multiline_arm |= source_map.is_multiline(*sp);
677 err.span_label(*sp, format!("this is found to be of type `{}`", t));
679 } else if let Some(sp) = prior_arms.last() {
680 any_multiline_arm |= source_map.is_multiline(*sp);
683 format!("this and all prior arms are found to be of type `{}`", t),
686 let outer_error_span = if any_multiline_arm {
687 // Cover just `match` and the scrutinee expression, not
688 // the entire match body, to reduce diagram noise.
689 cause.span.shrink_to_lo().to(scrut_span)
693 let msg = "`match` arms have incompatible types";
694 err.span_label(outer_error_span, msg);
695 if let Some((sp, boxed)) = semi_span {
696 if let (StatementAsExpression::NeedsBoxing, [.., prior_arm]) =
697 (boxed, &prior_arms[..])
699 err.multipart_suggestion(
700 "consider removing this semicolon and boxing the expressions",
702 (prior_arm.shrink_to_lo(), "Box::new(".to_string()),
703 (prior_arm.shrink_to_hi(), ")".to_string()),
704 (arm_span.shrink_to_lo(), "Box::new(".to_string()),
705 (arm_span.shrink_to_hi(), ")".to_string()),
708 Applicability::HasPlaceholders,
710 } else if matches!(boxed, StatementAsExpression::NeedsBoxing) {
711 err.span_suggestion_short(
713 "consider removing this semicolon and boxing the expressions",
715 Applicability::MachineApplicable,
718 err.span_suggestion_short(
720 "consider removing this semicolon",
722 Applicability::MachineApplicable,
726 if let Some(ret_sp) = opt_suggest_box_span {
727 // Get return type span and point to it.
728 self.suggest_boxing_for_return_impl_trait(
731 prior_arms.iter().chain(std::iter::once(&arm_span)).map(|s| *s),
736 ObligationCauseCode::IfExpression(box IfExpressionCause {
741 opt_suggest_box_span,
743 err.span_label(then, "expected because of this");
744 if let Some(sp) = outer {
745 err.span_label(sp, "`if` and `else` have incompatible types");
747 if let Some((sp, boxed)) = semicolon {
748 if matches!(boxed, StatementAsExpression::NeedsBoxing) {
749 err.multipart_suggestion(
750 "consider removing this semicolon and boxing the expression",
752 (then.shrink_to_lo(), "Box::new(".to_string()),
753 (then.shrink_to_hi(), ")".to_string()),
754 (else_sp.shrink_to_lo(), "Box::new(".to_string()),
755 (else_sp.shrink_to_hi(), ")".to_string()),
758 Applicability::MachineApplicable,
761 err.span_suggestion_short(
763 "consider removing this semicolon",
765 Applicability::MachineApplicable,
769 if let Some(ret_sp) = opt_suggest_box_span {
770 self.suggest_boxing_for_return_impl_trait(
773 [then, else_sp].into_iter(),
777 ObligationCauseCode::LetElse => {
778 err.help("try adding a diverging expression, such as `return` or `panic!(..)`");
779 err.help("...or use `match` instead of `let...else`");
782 if let ObligationCauseCode::BindingObligation(_, binding_span) =
783 cause.code().peel_derives()
785 if matches!(terr, TypeError::RegionsPlaceholderMismatch) {
786 err.span_note(*binding_span, "the lifetime requirement is introduced here");
793 fn suggest_boxing_for_return_impl_trait(
795 err: &mut DiagnosticBuilder<'tcx>,
797 arm_spans: impl Iterator<Item = Span>,
799 err.multipart_suggestion(
800 "you could change the return type to be a boxed trait object",
802 (return_sp.with_hi(return_sp.lo() + BytePos(4)), "Box<dyn".to_string()),
803 (return_sp.shrink_to_hi(), ">".to_string()),
805 Applicability::MaybeIncorrect,
809 [(sp.shrink_to_lo(), "Box::new(".to_string()), (sp.shrink_to_hi(), ")".to_string())]
812 .collect::<Vec<_>>();
813 err.multipart_suggestion(
814 "if you change the return type to expect trait objects, box the returned expressions",
816 Applicability::MaybeIncorrect,
820 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
821 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
822 /// populate `other_value` with `other_ty`.
826 /// ^^^^--------^ this is highlighted
828 /// | this type argument is exactly the same as the other type, not highlighted
829 /// this is highlighted
831 /// -------- this type is the same as a type argument in the other type, not highlighted
835 value: &mut DiagnosticStyledString,
836 other_value: &mut DiagnosticStyledString,
838 sub: ty::subst::SubstsRef<'tcx>,
842 // `value` and `other_value` hold two incomplete type representation for display.
843 // `name` is the path of both types being compared. `sub`
844 value.push_highlighted(name);
847 value.push_highlighted("<");
850 // Output the lifetimes for the first type
854 let s = lifetime.to_string();
855 if s.is_empty() { "'_".to_string() } else { s }
859 if !lifetimes.is_empty() {
860 if sub.regions().count() < len {
861 value.push_normal(lifetimes + ", ");
863 value.push_normal(lifetimes);
867 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
868 // `pos` and `other_ty`.
869 for (i, type_arg) in sub.types().enumerate() {
871 let values = self.cmp(type_arg, other_ty);
872 value.0.extend((values.0).0);
873 other_value.0.extend((values.1).0);
875 value.push_highlighted(type_arg.to_string());
878 if len > 0 && i != len - 1 {
879 value.push_normal(", ");
883 value.push_highlighted(">");
887 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
888 /// as that is the difference to the other type.
890 /// For the following code:
893 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
896 /// The type error output will behave in the following way:
900 /// ^^^^--------^ this is highlighted
902 /// | this type argument is exactly the same as the other type, not highlighted
903 /// this is highlighted
905 /// -------- this type is the same as a type argument in the other type, not highlighted
909 mut t1_out: &mut DiagnosticStyledString,
910 mut t2_out: &mut DiagnosticStyledString,
912 sub: ty::subst::SubstsRef<'tcx>,
916 for (i, ta) in sub.types().enumerate() {
918 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
921 if let ty::Adt(def, _) = ta.kind() {
922 let path_ = self.tcx.def_path_str(def.did);
923 if path_ == other_path {
924 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
932 /// Adds a `,` to the type representation only if it is appropriate.
935 value: &mut DiagnosticStyledString,
936 other_value: &mut DiagnosticStyledString,
940 if len > 0 && pos != len - 1 {
941 value.push_normal(", ");
942 other_value.push_normal(", ");
946 /// For generic types with parameters with defaults, remove the parameters corresponding to
947 /// the defaults. This repeats a lot of the logic found in `ty::print::pretty`.
948 fn strip_generic_default_params(
951 substs: ty::subst::SubstsRef<'tcx>,
952 ) -> SubstsRef<'tcx> {
953 let generics = self.tcx.generics_of(def_id);
954 let mut num_supplied_defaults = 0;
956 let default_params = generics.params.iter().rev().filter_map(|param| match param.kind {
957 ty::GenericParamDefKind::Type { has_default: true, .. } => Some(param.def_id),
958 ty::GenericParamDefKind::Const { has_default: true } => Some(param.def_id),
961 for (def_id, actual) in iter::zip(default_params, substs.iter().rev()) {
962 match actual.unpack() {
963 GenericArgKind::Const(c) => {
964 if self.tcx.const_param_default(def_id).subst(self.tcx, substs) != c {
968 GenericArgKind::Type(ty) => {
969 if self.tcx.type_of(def_id).subst(self.tcx, substs) != ty {
975 num_supplied_defaults += 1;
977 let len = generics.params.len();
978 let mut generics = generics.clone();
979 generics.params.truncate(len - num_supplied_defaults);
980 substs.truncate_to(self.tcx, &generics)
983 /// Given two `fn` signatures highlight only sub-parts that are different.
986 sig1: &ty::PolyFnSig<'tcx>,
987 sig2: &ty::PolyFnSig<'tcx>,
988 ) -> (DiagnosticStyledString, DiagnosticStyledString) {
989 let get_lifetimes = |sig| {
990 use rustc_hir::def::Namespace;
991 let mut s = String::new();
992 let (_, sig, reg) = ty::print::FmtPrinter::new(self.tcx, &mut s, Namespace::TypeNS)
993 .name_all_regions(sig)
995 let lts: Vec<String> = reg.into_iter().map(|(_, kind)| kind.to_string()).collect();
996 (if lts.is_empty() { String::new() } else { format!("for<{}> ", lts.join(", ")) }, sig)
999 let (lt1, sig1) = get_lifetimes(sig1);
1000 let (lt2, sig2) = get_lifetimes(sig2);
1002 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1004 DiagnosticStyledString::normal("".to_string()),
1005 DiagnosticStyledString::normal("".to_string()),
1008 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1010 values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1011 values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety);
1013 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1015 if sig1.abi != abi::Abi::Rust {
1016 values.0.push(format!("extern {} ", sig1.abi), sig1.abi != sig2.abi);
1018 if sig2.abi != abi::Abi::Rust {
1019 values.1.push(format!("extern {} ", sig2.abi), sig1.abi != sig2.abi);
1022 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1024 let lifetime_diff = lt1 != lt2;
1025 values.0.push(lt1, lifetime_diff);
1026 values.1.push(lt2, lifetime_diff);
1028 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1030 values.0.push_normal("fn(");
1031 values.1.push_normal("fn(");
1033 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1035 let len1 = sig1.inputs().len();
1036 let len2 = sig2.inputs().len();
1038 for (i, (l, r)) in iter::zip(sig1.inputs(), sig2.inputs()).enumerate() {
1039 let (x1, x2) = self.cmp(l, r);
1040 (values.0).0.extend(x1.0);
1041 (values.1).0.extend(x2.0);
1042 self.push_comma(&mut values.0, &mut values.1, len1, i);
1045 for (i, l) in sig1.inputs().iter().enumerate() {
1046 values.0.push_highlighted(l.to_string());
1048 values.0.push_highlighted(", ");
1051 for (i, r) in sig2.inputs().iter().enumerate() {
1052 values.1.push_highlighted(r.to_string());
1054 values.1.push_highlighted(", ");
1059 if sig1.c_variadic {
1061 values.0.push_normal(", ");
1063 values.0.push("...", !sig2.c_variadic);
1065 if sig2.c_variadic {
1067 values.1.push_normal(", ");
1069 values.1.push("...", !sig1.c_variadic);
1072 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1074 values.0.push_normal(")");
1075 values.1.push_normal(")");
1077 // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
1079 let output1 = sig1.output();
1080 let output2 = sig2.output();
1081 let (x1, x2) = self.cmp(output1, output2);
1082 if !output1.is_unit() {
1083 values.0.push_normal(" -> ");
1084 (values.0).0.extend(x1.0);
1086 if !output2.is_unit() {
1087 values.1.push_normal(" -> ");
1088 (values.1).0.extend(x2.0);
1093 /// Compares two given types, eliding parts that are the same between them and highlighting
1094 /// relevant differences, and return two representation of those types for highlighted printing.
1095 fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
1096 debug!("cmp(t1={}, t1.kind={:?}, t2={}, t2.kind={:?})", t1, t1.kind(), t2, t2.kind());
1099 fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
1100 match (a.kind(), b.kind()) {
1101 (a, b) if *a == *b => true,
1102 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
1104 &ty::Infer(ty::InferTy::IntVar(_)),
1105 &ty::Int(_) | &ty::Infer(ty::InferTy::IntVar(_)),
1107 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
1109 &ty::Infer(ty::InferTy::FloatVar(_)),
1110 &ty::Float(_) | &ty::Infer(ty::InferTy::FloatVar(_)),
1116 fn push_ty_ref<'tcx>(
1117 region: &ty::Region<'tcx>,
1119 mutbl: hir::Mutability,
1120 s: &mut DiagnosticStyledString,
1122 let mut r = region.to_string();
1128 s.push_highlighted(format!("&{}{}", r, mutbl.prefix_str()));
1129 s.push_normal(ty.to_string());
1132 // process starts here
1133 match (t1.kind(), t2.kind()) {
1134 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
1135 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
1136 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
1137 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1138 let path1 = self.tcx.def_path_str(def1.did);
1139 let path2 = self.tcx.def_path_str(def2.did);
1140 if def1.did == def2.did {
1141 // Easy case. Replace same types with `_` to shorten the output and highlight
1142 // the differing ones.
1143 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
1146 // --- ^ type argument elided
1148 // highlighted in output
1149 values.0.push_normal(path1);
1150 values.1.push_normal(path2);
1152 // Avoid printing out default generic parameters that are common to both
1154 let len1 = sub_no_defaults_1.len();
1155 let len2 = sub_no_defaults_2.len();
1156 let common_len = cmp::min(len1, len2);
1157 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
1158 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
1159 let common_default_params =
1160 iter::zip(remainder1.iter().rev(), remainder2.iter().rev())
1161 .filter(|(a, b)| a == b)
1163 let len = sub1.len() - common_default_params;
1164 let consts_offset = len - sub1.consts().count();
1166 // Only draw `<...>` if there're lifetime/type arguments.
1168 values.0.push_normal("<");
1169 values.1.push_normal("<");
1172 fn lifetime_display(lifetime: Region<'_>) -> String {
1173 let s = lifetime.to_string();
1174 if s.is_empty() { "'_".to_string() } else { s }
1176 // At one point we'd like to elide all lifetimes here, they are irrelevant for
1177 // all diagnostics that use this output
1181 // ^^ ^^ --- type arguments are not elided
1183 // | elided as they were the same
1184 // not elided, they were different, but irrelevant
1186 // For bound lifetimes, keep the names of the lifetimes,
1187 // even if they are the same so that it's clear what's happening
1188 // if we have something like
1190 // for<'r, 's> fn(Inv<'r>, Inv<'s>)
1191 // for<'r> fn(Inv<'r>, Inv<'r>)
1192 let lifetimes = sub1.regions().zip(sub2.regions());
1193 for (i, lifetimes) in lifetimes.enumerate() {
1194 let l1 = lifetime_display(lifetimes.0);
1195 let l2 = lifetime_display(lifetimes.1);
1196 if lifetimes.0 != lifetimes.1 {
1197 values.0.push_highlighted(l1);
1198 values.1.push_highlighted(l2);
1199 } else if lifetimes.0.is_late_bound() {
1200 values.0.push_normal(l1);
1201 values.1.push_normal(l2);
1203 values.0.push_normal("'_");
1204 values.1.push_normal("'_");
1206 self.push_comma(&mut values.0, &mut values.1, len, i);
1209 // We're comparing two types with the same path, so we compare the type
1210 // arguments for both. If they are the same, do not highlight and elide from the
1214 // ^ elided type as this type argument was the same in both sides
1215 let type_arguments = sub1.types().zip(sub2.types());
1216 let regions_len = sub1.regions().count();
1217 let num_display_types = consts_offset - regions_len;
1218 for (i, (ta1, ta2)) in type_arguments.take(num_display_types).enumerate() {
1219 let i = i + regions_len;
1221 values.0.push_normal("_");
1222 values.1.push_normal("_");
1224 let (x1, x2) = self.cmp(ta1, ta2);
1225 (values.0).0.extend(x1.0);
1226 (values.1).0.extend(x2.0);
1228 self.push_comma(&mut values.0, &mut values.1, len, i);
1231 // Do the same for const arguments, if they are equal, do not highlight and
1232 // elide them from the output.
1233 let const_arguments = sub1.consts().zip(sub2.consts());
1234 for (i, (ca1, ca2)) in const_arguments.enumerate() {
1235 let i = i + consts_offset;
1237 values.0.push_normal("_");
1238 values.1.push_normal("_");
1240 values.0.push_highlighted(ca1.to_string());
1241 values.1.push_highlighted(ca2.to_string());
1243 self.push_comma(&mut values.0, &mut values.1, len, i);
1246 // Close the type argument bracket.
1247 // Only draw `<...>` if there're lifetime/type arguments.
1249 values.0.push_normal(">");
1250 values.1.push_normal(">");
1255 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1257 // ------- this type argument is exactly the same as the other type
1273 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1276 // ------- this type argument is exactly the same as the other type
1291 // We can't find anything in common, highlight relevant part of type path.
1292 // let x: foo::bar::Baz<Qux> = y:<foo::bar::Bar<Zar>>();
1293 // foo::bar::Baz<Qux>
1294 // foo::bar::Bar<Zar>
1295 // -------- this part of the path is different
1297 let t1_str = t1.to_string();
1298 let t2_str = t2.to_string();
1299 let min_len = t1_str.len().min(t2_str.len());
1301 const SEPARATOR: &str = "::";
1302 let separator_len = SEPARATOR.len();
1303 let split_idx: usize =
1304 iter::zip(t1_str.split(SEPARATOR), t2_str.split(SEPARATOR))
1305 .take_while(|(mod1_str, mod2_str)| mod1_str == mod2_str)
1306 .map(|(mod_str, _)| mod_str.len() + separator_len)
1310 "cmp: separator_len={}, split_idx={}, min_len={}",
1311 separator_len, split_idx, min_len
1314 if split_idx >= min_len {
1315 // paths are identical, highlight everything
1317 DiagnosticStyledString::highlighted(t1_str),
1318 DiagnosticStyledString::highlighted(t2_str),
1321 let (common, uniq1) = t1_str.split_at(split_idx);
1322 let (_, uniq2) = t2_str.split_at(split_idx);
1323 debug!("cmp: common={}, uniq1={}, uniq2={}", common, uniq1, uniq2);
1325 values.0.push_normal(common);
1326 values.0.push_highlighted(uniq1);
1327 values.1.push_normal(common);
1328 values.1.push_highlighted(uniq2);
1335 // When finding T != &T, highlight only the borrow
1336 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
1337 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1338 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1339 values.1.push_normal(t2.to_string());
1342 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
1343 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1344 values.0.push_normal(t1.to_string());
1345 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1349 // When encountering &T != &mut T, highlight only the borrow
1350 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1351 if equals(&ref_ty1, &ref_ty2) =>
1353 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1354 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1355 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1359 // When encountering tuples of the same size, highlight only the differing types
1360 (&ty::Tuple(substs1), &ty::Tuple(substs2)) if substs1.len() == substs2.len() => {
1362 (DiagnosticStyledString::normal("("), DiagnosticStyledString::normal("("));
1363 let len = substs1.len();
1364 for (i, (left, right)) in substs1.types().zip(substs2.types()).enumerate() {
1365 let (x1, x2) = self.cmp(left, right);
1366 (values.0).0.extend(x1.0);
1367 (values.1).0.extend(x2.0);
1368 self.push_comma(&mut values.0, &mut values.1, len, i);
1371 // Keep the output for single element tuples as `(ty,)`.
1372 values.0.push_normal(",");
1373 values.1.push_normal(",");
1375 values.0.push_normal(")");
1376 values.1.push_normal(")");
1380 (ty::FnDef(did1, substs1), ty::FnDef(did2, substs2)) => {
1381 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1382 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1383 let mut values = self.cmp_fn_sig(&sig1, &sig2);
1384 let path1 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did1, substs1));
1385 let path2 = format!(" {{{}}}", self.tcx.def_path_str_with_substs(*did2, substs2));
1386 let same_path = path1 == path2;
1387 values.0.push(path1, !same_path);
1388 values.1.push(path2, !same_path);
1392 (ty::FnDef(did1, substs1), ty::FnPtr(sig2)) => {
1393 let sig1 = self.tcx.fn_sig(*did1).subst(self.tcx, substs1);
1394 let mut values = self.cmp_fn_sig(&sig1, sig2);
1395 values.0.push_highlighted(format!(
1397 self.tcx.def_path_str_with_substs(*did1, substs1)
1402 (ty::FnPtr(sig1), ty::FnDef(did2, substs2)) => {
1403 let sig2 = self.tcx.fn_sig(*did2).subst(self.tcx, substs2);
1404 let mut values = self.cmp_fn_sig(sig1, &sig2);
1405 values.1.push_normal(format!(
1407 self.tcx.def_path_str_with_substs(*did2, substs2)
1412 (ty::FnPtr(sig1), ty::FnPtr(sig2)) => self.cmp_fn_sig(sig1, sig2),
1416 // The two types are the same, elide and don't highlight.
1417 (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
1419 // We couldn't find anything in common, highlight everything.
1421 DiagnosticStyledString::highlighted(t1.to_string()),
1422 DiagnosticStyledString::highlighted(t2.to_string()),
1429 /// Extend a type error with extra labels pointing at "non-trivial" types, like closures and
1430 /// the return type of `async fn`s.
1432 /// `secondary_span` gives the caller the opportunity to expand `diag` with a `span_label`.
1434 /// `swap_secondary_and_primary` is used to make projection errors in particular nicer by using
1435 /// the message in `secondary_span` as the primary label, and apply the message that would
1436 /// otherwise be used for the primary label on the `secondary_span` `Span`. This applies on
1437 /// E0271, like `src/test/ui/issues/issue-39970.stderr`.
1438 pub fn note_type_err(
1440 diag: &mut DiagnosticBuilder<'tcx>,
1441 cause: &ObligationCause<'tcx>,
1442 secondary_span: Option<(Span, String)>,
1443 mut values: Option<ValuePairs<'tcx>>,
1444 terr: &TypeError<'tcx>,
1445 swap_secondary_and_primary: bool,
1447 let span = cause.span(self.tcx);
1448 debug!("note_type_err cause={:?} values={:?}, terr={:?}", cause, values, terr);
1450 // For some types of errors, expected-found does not make
1451 // sense, so just ignore the values we were given.
1452 if let TypeError::CyclicTy(_) = terr {
1455 struct OpaqueTypesVisitor<'tcx> {
1456 types: FxHashMap<TyCategory, FxHashSet<Span>>,
1457 expected: FxHashMap<TyCategory, FxHashSet<Span>>,
1458 found: FxHashMap<TyCategory, FxHashSet<Span>>,
1463 impl<'tcx> OpaqueTypesVisitor<'tcx> {
1464 fn visit_expected_found(
1470 let mut types_visitor = OpaqueTypesVisitor {
1471 types: Default::default(),
1472 expected: Default::default(),
1473 found: Default::default(),
1477 // The visitor puts all the relevant encountered types in `self.types`, but in
1478 // here we want to visit two separate types with no relation to each other, so we
1479 // move the results from `types` to `expected` or `found` as appropriate.
1480 expected.visit_with(&mut types_visitor);
1481 std::mem::swap(&mut types_visitor.expected, &mut types_visitor.types);
1482 found.visit_with(&mut types_visitor);
1483 std::mem::swap(&mut types_visitor.found, &mut types_visitor.types);
1487 fn report(&self, err: &mut DiagnosticBuilder<'_>) {
1488 self.add_labels_for_types(err, "expected", &self.expected);
1489 self.add_labels_for_types(err, "found", &self.found);
1492 fn add_labels_for_types(
1494 err: &mut DiagnosticBuilder<'_>,
1496 types: &FxHashMap<TyCategory, FxHashSet<Span>>,
1498 for (key, values) in types.iter() {
1499 let count = values.len();
1500 let kind = key.descr();
1501 let mut returned_async_output_error = false;
1503 if sp.is_desugaring(DesugaringKind::Async) && !returned_async_output_error {
1504 if [sp] != err.span.primary_spans() {
1505 let mut span: MultiSpan = sp.into();
1506 span.push_span_label(
1509 "checked the `Output` of this `async fn`, {}{} {}{}",
1510 if count > 1 { "one of the " } else { "" },
1518 "while checking the return type of the `async fn`",
1524 "checked the `Output` of this `async fn`, {}{} {}{}",
1525 if count > 1 { "one of the " } else { "" },
1531 err.note("while checking the return type of the `async fn`");
1533 returned_async_output_error = true;
1539 if count == 1 { "the " } else { "one of the " },
1551 impl<'tcx> ty::fold::TypeVisitor<'tcx> for OpaqueTypesVisitor<'tcx> {
1552 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
1553 if let Some((kind, def_id)) = TyCategory::from_ty(self.tcx, t) {
1554 let span = self.tcx.def_span(def_id);
1555 // Avoid cluttering the output when the "found" and error span overlap:
1557 // error[E0308]: mismatched types
1558 // --> $DIR/issue-20862.rs:2:5
1563 // | the found closure
1564 // | expected `()`, found closure
1566 // = note: expected unit type `()`
1567 // found closure `[closure@$DIR/issue-20862.rs:2:5: 2:14 x:_]`
1568 if !self.ignore_span.overlaps(span) {
1569 self.types.entry(kind).or_default().insert(span);
1572 t.super_visit_with(self)
1576 debug!("note_type_err(diag={:?})", diag);
1578 Variable(ty::error::ExpectedFound<Ty<'a>>),
1579 Fixed(&'static str),
1581 let (expected_found, exp_found, is_simple_error) = match values {
1582 None => (None, Mismatch::Fixed("type"), false),
1584 let (is_simple_error, exp_found) = match values {
1585 ValuePairs::Types(exp_found) => {
1587 exp_found.expected.is_simple_text() && exp_found.found.is_simple_text();
1588 OpaqueTypesVisitor::visit_expected_found(
1596 (is_simple_err, Mismatch::Variable(exp_found))
1598 ValuePairs::TraitRefs(_) => (false, Mismatch::Fixed("trait")),
1599 _ => (false, Mismatch::Fixed("type")),
1601 let vals = match self.values_str(values) {
1602 Some((expected, found)) => Some((expected, found)),
1604 // Derived error. Cancel the emitter.
1609 (vals, exp_found, is_simple_error)
1613 // Ignore msg for object safe coercion
1614 // since E0038 message will be printed
1616 TypeError::ObjectUnsafeCoercion(_) => {}
1618 let mut label_or_note = |span: Span, msg: &str| {
1619 if &[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::Types(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_as_ref_where_appropriate(span, &exp_found, diag);
1738 self.suggest_accessing_field_where_appropriate(cause, &exp_found, diag);
1739 self.suggest_await_on_expect_found(cause, span, &exp_found, diag);
1743 // In some (most?) cases cause.body_id points to actual body, but in some cases
1744 // it's an actual definition. According to the comments (e.g. in
1745 // librustc_typeck/check/compare_method.rs:compare_predicate_entailment) the latter
1746 // is relied upon by some other code. This might (or might not) need cleanup.
1747 let body_owner_def_id =
1748 self.tcx.hir().opt_local_def_id(cause.body_id).unwrap_or_else(|| {
1749 self.tcx.hir().body_owner_def_id(hir::BodyId { hir_id: cause.body_id })
1751 self.check_and_note_conflicting_crates(diag, terr);
1752 self.tcx.note_and_explain_type_err(diag, terr, cause, span, body_owner_def_id.to_def_id());
1754 if let Some(ValuePairs::PolyTraitRefs(exp_found)) = values {
1755 if let ty::Closure(def_id, _) = exp_found.expected.skip_binder().self_ty().kind() {
1756 if let Some(def_id) = def_id.as_local() {
1757 let span = self.tcx.def_span(def_id);
1758 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);
1768 pub fn get_impl_future_output_ty(&self, ty: Ty<'tcx>) -> Option<Binder<'tcx, Ty<'tcx>>> {
1769 if let ty::Opaque(def_id, substs) = ty.kind() {
1770 let future_trait = self.tcx.require_lang_item(LangItem::Future, None);
1772 let item_def_id = self.tcx.associated_item_def_ids(future_trait)[0];
1774 let bounds = self.tcx.explicit_item_bounds(*def_id);
1776 for (predicate, _) in bounds {
1777 let predicate = predicate.subst(self.tcx, substs);
1778 let output = predicate
1780 .map_bound(|kind| match kind {
1781 ty::PredicateKind::Projection(projection_predicate)
1782 if projection_predicate.projection_ty.item_def_id == item_def_id =>
1784 projection_predicate.term.ty()
1789 if output.is_some() {
1790 // We don't account for multiple `Future::Output = Ty` contraints.
1798 /// A possible error is to forget to add `.await` when using futures:
1801 /// async fn make_u32() -> u32 {
1805 /// fn take_u32(x: u32) {}
1807 /// async fn foo() {
1808 /// let x = make_u32();
1813 /// This routine checks if the found type `T` implements `Future<Output=U>` where `U` is the
1814 /// expected type. If this is the case, and we are inside of an async body, it suggests adding
1815 /// `.await` to the tail of the expression.
1816 fn suggest_await_on_expect_found(
1818 cause: &ObligationCause<'tcx>,
1820 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1821 diag: &mut DiagnosticBuilder<'tcx>,
1824 "suggest_await_on_expect_found: exp_span={:?}, expected_ty={:?}, found_ty={:?}",
1825 exp_span, exp_found.expected, exp_found.found,
1828 if let ObligationCauseCode::CompareImplMethodObligation { .. } = cause.code() {
1833 self.get_impl_future_output_ty(exp_found.expected).map(Binder::skip_binder),
1834 self.get_impl_future_output_ty(exp_found.found).map(Binder::skip_binder),
1836 (Some(exp), Some(found)) if same_type_modulo_infer(exp, found) => match cause.code() {
1837 ObligationCauseCode::IfExpression(box IfExpressionCause { then, .. }) => {
1838 diag.multipart_suggestion(
1839 "consider `await`ing on both `Future`s",
1841 (then.shrink_to_hi(), ".await".to_string()),
1842 (exp_span.shrink_to_hi(), ".await".to_string()),
1844 Applicability::MaybeIncorrect,
1847 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1851 if let [.., arm_span] = &prior_arms[..] {
1852 diag.multipart_suggestion(
1853 "consider `await`ing on both `Future`s",
1855 (arm_span.shrink_to_hi(), ".await".to_string()),
1856 (exp_span.shrink_to_hi(), ".await".to_string()),
1858 Applicability::MaybeIncorrect,
1861 diag.help("consider `await`ing on both `Future`s");
1865 diag.help("consider `await`ing on both `Future`s");
1868 (_, Some(ty)) if same_type_modulo_infer(exp_found.expected, ty) => {
1869 diag.span_suggestion_verbose(
1870 exp_span.shrink_to_hi(),
1871 "consider `await`ing on the `Future`",
1872 ".await".to_string(),
1873 Applicability::MaybeIncorrect,
1876 (Some(ty), _) if same_type_modulo_infer(ty, exp_found.found) => match cause.code() {
1877 ObligationCauseCode::Pattern { span: Some(span), .. }
1878 | ObligationCauseCode::IfExpression(box IfExpressionCause { then: span, .. }) => {
1879 diag.span_suggestion_verbose(
1880 span.shrink_to_hi(),
1881 "consider `await`ing on the `Future`",
1882 ".await".to_string(),
1883 Applicability::MaybeIncorrect,
1886 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
1890 diag.multipart_suggestion_verbose(
1891 "consider `await`ing on the `Future`",
1894 .map(|arm| (arm.shrink_to_hi(), ".await".to_string()))
1896 Applicability::MaybeIncorrect,
1905 fn suggest_accessing_field_where_appropriate(
1907 cause: &ObligationCause<'tcx>,
1908 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1909 diag: &mut DiagnosticBuilder<'tcx>,
1912 "suggest_accessing_field_where_appropriate(cause={:?}, exp_found={:?})",
1915 if let ty::Adt(expected_def, expected_substs) = exp_found.expected.kind() {
1916 if expected_def.is_enum() {
1920 if let Some((name, ty)) = expected_def
1924 .filter(|field| field.vis.is_accessible_from(field.did, self.tcx))
1925 .map(|field| (field.name, field.ty(self.tcx, expected_substs)))
1926 .find(|(_, ty)| same_type_modulo_infer(ty, exp_found.found))
1928 if let ObligationCauseCode::Pattern { span: Some(span), .. } = *cause.code() {
1929 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
1930 let suggestion = if expected_def.is_struct() {
1931 format!("{}.{}", snippet, name)
1932 } else if expected_def.is_union() {
1933 format!("unsafe {{ {}.{} }}", snippet, name)
1937 diag.span_suggestion(
1940 "you might have meant to use field `{}` whose type is `{}`",
1944 Applicability::MaybeIncorrect,
1952 /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1954 fn suggest_as_ref_where_appropriate(
1957 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1958 diag: &mut DiagnosticBuilder<'tcx>,
1960 if let (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) =
1961 (exp_found.expected.kind(), exp_found.found.kind())
1963 if let ty::Adt(found_def, found_substs) = *found_ty.kind() {
1964 let path_str = format!("{:?}", exp_def);
1965 if exp_def == &found_def {
1966 let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1968 let result_msg = "you can convert from `&Result<T, E>` to \
1969 `Result<&T, &E>` using `.as_ref()`";
1970 let have_as_ref = &[
1971 ("std::option::Option", opt_msg),
1972 ("core::option::Option", opt_msg),
1973 ("std::result::Result", result_msg),
1974 ("core::result::Result", result_msg),
1976 if let Some(msg) = have_as_ref
1978 .find_map(|(path, msg)| (&path_str == path).then_some(msg))
1980 let mut show_suggestion = true;
1981 for (exp_ty, found_ty) in
1982 iter::zip(exp_substs.types(), found_substs.types())
1984 match *exp_ty.kind() {
1985 ty::Ref(_, exp_ty, _) => {
1986 match (exp_ty.kind(), found_ty.kind()) {
1990 | (ty::Infer(_), _) => {}
1991 _ if same_type_modulo_infer(exp_ty, found_ty) => {}
1992 _ => show_suggestion = false,
1995 ty::Param(_) | ty::Infer(_) => {}
1996 _ => show_suggestion = false,
1999 if let (Ok(snippet), true) =
2000 (self.tcx.sess.source_map().span_to_snippet(span), show_suggestion)
2002 diag.span_suggestion(
2005 format!("{}.as_ref()", snippet),
2006 Applicability::MachineApplicable,
2015 pub fn report_and_explain_type_error(
2017 trace: TypeTrace<'tcx>,
2018 terr: &TypeError<'tcx>,
2019 ) -> DiagnosticBuilder<'tcx> {
2020 use crate::traits::ObligationCauseCode::MatchExpressionArm;
2022 debug!("report_and_explain_type_error(trace={:?}, terr={:?})", trace, terr);
2024 let span = trace.cause.span(self.tcx);
2025 let failure_code = trace.cause.as_failure_code(terr);
2026 let mut diag = match failure_code {
2027 FailureCode::Error0038(did) => {
2028 let violations = self.tcx.object_safety_violations(did);
2029 report_object_safety_error(self.tcx, span, did, violations)
2031 FailureCode::Error0317(failure_str) => {
2032 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
2034 FailureCode::Error0580(failure_str) => {
2035 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
2037 FailureCode::Error0308(failure_str) => {
2038 let mut err = struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str);
2039 if let ValuePairs::Types(ty::error::ExpectedFound { expected, found }) =
2042 match (expected.kind(), found.kind()) {
2043 (ty::Tuple(_), ty::Tuple(_)) => {}
2044 // If a tuple of length one was expected and the found expression has
2045 // parentheses around it, perhaps the user meant to write `(expr,)` to
2046 // build a tuple (issue #86100)
2047 (ty::Tuple(_), _) if expected.tuple_fields().count() == 1 => {
2048 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
2050 code.strip_prefix('(').and_then(|s| s.strip_suffix(')'))
2052 err.span_suggestion(
2054 "use a trailing comma to create a tuple with one element",
2055 format!("({},)", code),
2056 Applicability::MaybeIncorrect,
2061 // If a character was expected and the found expression is a string literal
2062 // containing a single character, perhaps the user meant to write `'c'` to
2063 // specify a character literal (issue #92479)
2064 (ty::Char, ty::Ref(_, r, _)) if r.is_str() => {
2065 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
2067 code.strip_prefix('"').and_then(|s| s.strip_suffix('"'))
2069 if code.chars().nth(1).is_none() {
2070 err.span_suggestion(
2072 "if you meant to write a `char` literal, use single quotes",
2073 format!("'{}'", code),
2074 Applicability::MachineApplicable,
2080 // If a string was expected and the found expression is a character literal,
2081 // perhaps the user meant to write `"s"` to specify a string literal.
2082 (ty::Ref(_, r, _), ty::Char) if r.is_str() => {
2083 if let Ok(code) = self.tcx.sess().source_map().span_to_snippet(span) {
2085 code.strip_prefix('\'').and_then(|s| s.strip_suffix('\''))
2087 err.span_suggestion(
2089 "if you meant to write a `str` literal, use double quotes",
2090 format!("\"{}\"", code),
2091 Applicability::MachineApplicable,
2099 if let MatchExpressionArm(box MatchExpressionArmCause { source, .. }) =
2102 if let hir::MatchSource::TryDesugar = source {
2103 if let Some((expected_ty, found_ty)) = self.values_str(trace.values) {
2105 "`?` operator cannot convert from `{}` to `{}`",
2107 expected_ty.content(),
2114 FailureCode::Error0644(failure_str) => {
2115 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
2118 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr, false);
2124 values: ValuePairs<'tcx>,
2125 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2127 infer::Types(exp_found) => self.expected_found_str_ty(exp_found),
2128 infer::Regions(exp_found) => self.expected_found_str(exp_found),
2129 infer::Consts(exp_found) => self.expected_found_str(exp_found),
2130 infer::TraitRefs(exp_found) => {
2131 let pretty_exp_found = ty::error::ExpectedFound {
2132 expected: exp_found.expected.print_only_trait_path(),
2133 found: exp_found.found.print_only_trait_path(),
2135 match self.expected_found_str(pretty_exp_found) {
2136 Some((expected, found)) if expected == found => {
2137 self.expected_found_str(exp_found)
2142 infer::PolyTraitRefs(exp_found) => {
2143 let pretty_exp_found = ty::error::ExpectedFound {
2144 expected: exp_found.expected.print_only_trait_path(),
2145 found: exp_found.found.print_only_trait_path(),
2147 match self.expected_found_str(pretty_exp_found) {
2148 Some((expected, found)) if expected == found => {
2149 self.expected_found_str(exp_found)
2157 fn expected_found_str_ty(
2159 exp_found: ty::error::ExpectedFound<Ty<'tcx>>,
2160 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2161 let exp_found = self.resolve_vars_if_possible(exp_found);
2162 if exp_found.references_error() {
2166 Some(self.cmp(exp_found.expected, exp_found.found))
2169 /// Returns a string of the form "expected `{}`, found `{}`".
2170 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
2172 exp_found: ty::error::ExpectedFound<T>,
2173 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
2174 let exp_found = self.resolve_vars_if_possible(exp_found);
2175 if exp_found.references_error() {
2180 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
2181 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
2185 pub fn report_generic_bound_failure(
2188 origin: Option<SubregionOrigin<'tcx>>,
2189 bound_kind: GenericKind<'tcx>,
2192 self.construct_generic_bound_failure(span, origin, bound_kind, sub).emit();
2195 pub fn construct_generic_bound_failure(
2198 origin: Option<SubregionOrigin<'tcx>>,
2199 bound_kind: GenericKind<'tcx>,
2201 ) -> DiagnosticBuilder<'a> {
2202 let hir = &self.tcx.hir();
2203 // Attempt to obtain the span of the parameter so we can
2204 // suggest adding an explicit lifetime bound to it.
2206 .in_progress_typeck_results
2207 .map(|typeck_results| typeck_results.borrow().hir_owner)
2209 let hir_id = hir.local_def_id_to_hir_id(owner);
2210 let parent_id = hir.get_parent_item(hir_id);
2212 // Parent item could be a `mod`, so we check the HIR before calling:
2213 if let Some(Node::Item(Item {
2214 kind: ItemKind::Trait(..) | ItemKind::Impl { .. },
2216 })) = hir.find_by_def_id(parent_id)
2218 Some(self.tcx.generics_of(parent_id))
2222 self.tcx.generics_of(owner.to_def_id()),
2227 let span = match generics {
2228 // This is to get around the trait identity obligation, that has a `DUMMY_SP` as signal
2229 // for other diagnostics, so we need to recover it here.
2230 Some((_, _, node)) if span.is_dummy() => node,
2234 let type_param_span = match (generics, bound_kind) {
2235 (Some((_, ref generics, _)), GenericKind::Param(ref param)) => {
2236 // Account for the case where `param` corresponds to `Self`,
2237 // which doesn't have the expected type argument.
2238 if !(generics.has_self && param.index == 0) {
2239 let type_param = generics.type_param(param, self.tcx);
2240 type_param.def_id.as_local().map(|def_id| {
2241 // Get the `hir::Param` to verify whether it already has any bounds.
2242 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
2243 // instead we suggest `T: 'a + 'b` in that case.
2244 let id = hir.local_def_id_to_hir_id(def_id);
2245 let mut has_bounds = false;
2246 if let Node::GenericParam(param) = hir.get(id) {
2247 has_bounds = !param.bounds.is_empty();
2249 let sp = self.tcx.def_span(def_id);
2250 // `sp` only covers `T`, change it so that it covers
2251 // `T:` when appropriate
2252 let is_impl_trait = bound_kind.to_string().starts_with("impl ");
2253 let sp = if has_bounds && !is_impl_trait {
2258 .next_point(self.tcx.sess.source_map().next_point(sp)))
2262 (sp, has_bounds, is_impl_trait)
2270 let new_lt = generics
2272 .and_then(|(parent_g, g, _)| {
2273 let mut possible = (b'a'..=b'z').map(|c| format!("'{}", c as char));
2274 let mut lts_names = g
2277 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2278 .map(|p| p.name.as_str())
2279 .collect::<Vec<_>>();
2280 if let Some(g) = parent_g {
2284 .filter(|p| matches!(p.kind, ty::GenericParamDefKind::Lifetime))
2285 .map(|p| p.name.as_str()),
2288 possible.find(|candidate| !lts_names.contains(&&candidate[..]))
2290 .unwrap_or("'lt".to_string());
2291 let add_lt_sugg = generics
2293 .and_then(|(_, g, _)| g.params.first())
2294 .and_then(|param| param.def_id.as_local())
2295 .map(|def_id| (self.tcx.def_span(def_id).shrink_to_lo(), format!("{}, ", new_lt)));
2297 let labeled_user_string = match bound_kind {
2298 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
2299 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
2302 if let Some(SubregionOrigin::CompareImplMethodObligation {
2308 return self.report_extra_impl_obligation(
2312 &format!("`{}: {}`", bound_kind, sub),
2316 fn binding_suggestion<'tcx, S: fmt::Display>(
2317 err: &mut DiagnosticBuilder<'tcx>,
2318 type_param_span: Option<(Span, bool, bool)>,
2319 bound_kind: GenericKind<'tcx>,
2322 let msg = "consider adding an explicit lifetime bound";
2323 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
2324 let suggestion = if is_impl_trait {
2325 format!("{} + {}", bound_kind, sub)
2327 let tail = if has_lifetimes { " + " } else { "" };
2328 format!("{}: {}{}", bound_kind, sub, tail)
2330 err.span_suggestion(
2332 &format!("{}...", msg),
2334 Applicability::MaybeIncorrect, // Issue #41966
2337 let consider = format!(
2340 if type_param_span.map_or(false, |(_, _, is_impl_trait)| is_impl_trait) {
2341 format!(" `{}` to `{}`", sub, bound_kind)
2343 format!("`{}: {}`", bound_kind, sub)
2346 err.help(&consider);
2350 let new_binding_suggestion =
2351 |err: &mut DiagnosticBuilder<'tcx>,
2352 type_param_span: Option<(Span, bool, bool)>,
2353 bound_kind: GenericKind<'tcx>| {
2354 let msg = "consider introducing an explicit lifetime bound";
2355 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
2356 let suggestion = if is_impl_trait {
2357 (sp.shrink_to_hi(), format!(" + {}", new_lt))
2359 let tail = if has_lifetimes { " +" } else { "" };
2360 (sp, format!("{}: {}{}", bound_kind, new_lt, tail))
2363 vec![suggestion, (span.shrink_to_hi(), format!(" + {}", new_lt))];
2364 if let Some(lt) = add_lt_sugg {
2366 sugg.rotate_right(1);
2368 // `MaybeIncorrect` due to issue #41966.
2369 err.multipart_suggestion(msg, sugg, Applicability::MaybeIncorrect);
2374 enum SubOrigin<'hir> {
2375 GAT(&'hir hir::Generics<'hir>),
2376 Impl(&'hir hir::Generics<'hir>),
2377 Trait(&'hir hir::Generics<'hir>),
2378 Fn(&'hir hir::Generics<'hir>),
2381 let sub_origin = 'origin: {
2383 ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, .. }) => {
2384 let node = self.tcx.hir().get_if_local(def_id).unwrap();
2386 Node::GenericParam(param) => {
2387 for h in self.tcx.hir().parent_iter(param.hir_id) {
2388 break 'origin match h.1 {
2389 Node::ImplItem(hir::ImplItem {
2390 kind: hir::ImplItemKind::TyAlias(..),
2393 }) => SubOrigin::GAT(generics),
2394 Node::ImplItem(hir::ImplItem {
2395 kind: hir::ImplItemKind::Fn(..),
2398 }) => SubOrigin::Fn(generics),
2399 Node::TraitItem(hir::TraitItem {
2400 kind: hir::TraitItemKind::Type(..),
2403 }) => SubOrigin::GAT(generics),
2404 Node::TraitItem(hir::TraitItem {
2405 kind: hir::TraitItemKind::Fn(..),
2408 }) => SubOrigin::Fn(generics),
2409 Node::Item(hir::Item {
2410 kind: hir::ItemKind::Trait(_, _, generics, _, _),
2412 }) => SubOrigin::Trait(generics),
2413 Node::Item(hir::Item {
2414 kind: hir::ItemKind::Impl(hir::Impl { generics, .. }),
2416 }) => SubOrigin::Impl(generics),
2417 Node::Item(hir::Item {
2418 kind: hir::ItemKind::Fn(_, generics, _),
2420 }) => SubOrigin::Fn(generics),
2432 debug!(?sub_origin);
2434 let mut err = match (*sub, sub_origin) {
2435 // In the case of GATs, we have to be careful. If we a type parameter `T` on an impl,
2436 // but a lifetime `'a` on an associated type, then we might need to suggest adding
2437 // `where T: 'a`. Importantly, this is on the GAT span, not on the `T` declaration.
2438 (ty::ReEarlyBound(ty::EarlyBoundRegion { name: _, .. }), SubOrigin::GAT(generics)) => {
2439 // Does the required lifetime have a nice name we can print?
2440 let mut err = struct_span_err!(
2444 "{} may not live long enough",
2447 let pred = format!("{}: {}", bound_kind, sub);
2448 let suggestion = format!(
2450 if !generics.where_clause.predicates.is_empty() { "," } else { " where" },
2453 err.span_suggestion(
2454 generics.where_clause.tail_span_for_suggestion(),
2455 "consider adding a where clause",
2457 Applicability::MaybeIncorrect,
2462 ty::ReEarlyBound(ty::EarlyBoundRegion { name, .. })
2463 | ty::ReFree(ty::FreeRegion { bound_region: ty::BrNamed(_, name), .. }),
2466 // Does the required lifetime have a nice name we can print?
2467 let mut err = struct_span_err!(
2471 "{} may not live long enough",
2474 // Explicitly use the name instead of `sub`'s `Display` impl. The `Display` impl
2475 // for the bound is not suitable for suggestions when `-Zverbose` is set because it
2476 // uses `Debug` output, so we handle it specially here so that suggestions are
2478 binding_suggestion(&mut err, type_param_span, bound_kind, name);
2482 (ty::ReStatic, _) => {
2483 // Does the required lifetime have a nice name we can print?
2484 let mut err = struct_span_err!(
2488 "{} may not live long enough",
2491 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
2496 // If not, be less specific.
2497 let mut err = struct_span_err!(
2501 "{} may not live long enough",
2504 note_and_explain_region(
2507 &format!("{} must be valid for ", labeled_user_string),
2512 if let Some(infer::RelateParamBound(_, t, _)) = origin {
2513 let return_impl_trait = self
2514 .in_progress_typeck_results
2515 .map(|typeck_results| typeck_results.borrow().hir_owner)
2516 .and_then(|owner| self.tcx.return_type_impl_trait(owner))
2518 let t = self.resolve_vars_if_possible(t);
2521 // fn get_later<G, T>(g: G, dest: &mut T) -> impl FnOnce() + '_
2523 // fn get_later<'a, G: 'a, T>(g: G, dest: &mut T) -> impl FnOnce() + '_ + 'a
2524 ty::Closure(_, _substs) | ty::Opaque(_, _substs) if return_impl_trait => {
2525 new_binding_suggestion(&mut err, type_param_span, bound_kind);
2528 binding_suggestion(&mut err, type_param_span, bound_kind, new_lt);
2536 if let Some(origin) = origin {
2537 self.note_region_origin(&mut err, &origin);
2542 fn report_sub_sup_conflict(
2544 var_origin: RegionVariableOrigin,
2545 sub_origin: SubregionOrigin<'tcx>,
2546 sub_region: Region<'tcx>,
2547 sup_origin: SubregionOrigin<'tcx>,
2548 sup_region: Region<'tcx>,
2550 let mut err = self.report_inference_failure(var_origin);
2552 note_and_explain_region(
2555 "first, the lifetime cannot outlive ",
2561 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
2562 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
2563 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
2564 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
2565 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
2567 if let (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) =
2568 (&sup_origin, &sub_origin)
2570 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
2571 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
2572 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
2573 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
2575 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) =
2576 (self.values_str(sup_trace.values), self.values_str(sub_trace.values))
2578 if sub_expected == sup_expected && sub_found == sup_found {
2579 note_and_explain_region(
2582 "...but the lifetime must also be valid for ",
2588 sup_trace.cause.span,
2589 &format!("...so that the {}", sup_trace.cause.as_requirement_str()),
2592 err.note_expected_found(&"", sup_expected, &"", sup_found);
2599 self.note_region_origin(&mut err, &sup_origin);
2601 note_and_explain_region(
2604 "but, the lifetime must be valid for ",
2610 self.note_region_origin(&mut err, &sub_origin);
2614 /// Determine whether an error associated with the given span and definition
2615 /// should be treated as being caused by the implicit `From` conversion
2616 /// within `?` desugaring.
2617 pub fn is_try_conversion(&self, span: Span, trait_def_id: DefId) -> bool {
2618 span.is_desugaring(DesugaringKind::QuestionMark)
2619 && self.tcx.is_diagnostic_item(sym::From, trait_def_id)
2623 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
2624 fn report_inference_failure(
2626 var_origin: RegionVariableOrigin,
2627 ) -> DiagnosticBuilder<'tcx> {
2628 let br_string = |br: ty::BoundRegionKind| {
2629 let mut s = match br {
2630 ty::BrNamed(_, name) => name.to_string(),
2638 let var_description = match var_origin {
2639 infer::MiscVariable(_) => String::new(),
2640 infer::PatternRegion(_) => " for pattern".to_string(),
2641 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
2642 infer::Autoref(_) => " for autoref".to_string(),
2643 infer::Coercion(_) => " for automatic coercion".to_string(),
2644 infer::LateBoundRegion(_, br, infer::FnCall) => {
2645 format!(" for lifetime parameter {}in function call", br_string(br))
2647 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
2648 format!(" for lifetime parameter {}in generic type", br_string(br))
2650 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
2651 " for lifetime parameter {}in trait containing associated type `{}`",
2653 self.tcx.associated_item(def_id).name
2655 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
2656 infer::UpvarRegion(ref upvar_id, _) => {
2657 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
2658 format!(" for capture of `{}` by closure", var_name)
2660 infer::Nll(..) => bug!("NLL variable found in lexical phase"),
2667 "cannot infer an appropriate lifetime{} due to conflicting requirements",
2675 Error0317(&'static str),
2676 Error0580(&'static str),
2677 Error0308(&'static str),
2678 Error0644(&'static str),
2681 trait ObligationCauseExt<'tcx> {
2682 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode;
2683 fn as_requirement_str(&self) -> &'static str;
2686 impl<'tcx> ObligationCauseExt<'tcx> for ObligationCause<'tcx> {
2687 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
2688 use self::FailureCode::*;
2689 use crate::traits::ObligationCauseCode::*;
2691 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
2692 CompareImplTypeObligation { .. } => Error0308("type not compatible with trait"),
2693 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => {
2694 Error0308(match source {
2695 hir::MatchSource::TryDesugar => "`?` operator has incompatible types",
2696 _ => "`match` arms have incompatible types",
2699 IfExpression { .. } => Error0308("`if` and `else` have incompatible types"),
2700 IfExpressionWithNoElse => Error0317("`if` may be missing an `else` clause"),
2701 LetElse => Error0308("`else` clause of `let...else` does not diverge"),
2702 MainFunctionType => Error0580("`main` function has wrong type"),
2703 StartFunctionType => Error0308("`#[start]` function has wrong type"),
2704 IntrinsicType => Error0308("intrinsic has wrong type"),
2705 MethodReceiver => Error0308("mismatched `self` parameter type"),
2707 // In the case where we have no more specific thing to
2708 // say, also take a look at the error code, maybe we can
2711 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
2712 Error0644("closure/generator type that references itself")
2714 TypeError::IntrinsicCast => {
2715 Error0308("cannot coerce intrinsics to function pointers")
2717 TypeError::ObjectUnsafeCoercion(did) => Error0038(*did),
2718 _ => Error0308("mismatched types"),
2723 fn as_requirement_str(&self) -> &'static str {
2724 use crate::traits::ObligationCauseCode::*;
2726 CompareImplMethodObligation { .. } => "method type is compatible with trait",
2727 CompareImplTypeObligation { .. } => "associated type is compatible with trait",
2728 ExprAssignable => "expression is assignable",
2729 IfExpression { .. } => "`if` and `else` have incompatible types",
2730 IfExpressionWithNoElse => "`if` missing an `else` returns `()`",
2731 MainFunctionType => "`main` function has the correct type",
2732 StartFunctionType => "`#[start]` function has the correct type",
2733 IntrinsicType => "intrinsic has the correct type",
2734 MethodReceiver => "method receiver has the correct type",
2735 _ => "types are compatible",
2740 /// This is a bare signal of what kind of type we're dealing with. `ty::TyKind` tracks
2741 /// extra information about each type, but we only care about the category.
2742 #[derive(Clone, Copy, PartialEq, Eq, Hash)]
2743 pub enum TyCategory {
2746 Generator(hir::GeneratorKind),
2751 fn descr(&self) -> &'static str {
2753 Self::Closure => "closure",
2754 Self::Opaque => "opaque type",
2755 Self::Generator(gk) => gk.descr(),
2756 Self::Foreign => "foreign type",
2760 pub fn from_ty(tcx: TyCtxt<'_>, ty: Ty<'_>) -> Option<(Self, DefId)> {
2762 ty::Closure(def_id, _) => Some((Self::Closure, def_id)),
2763 ty::Opaque(def_id, _) => Some((Self::Opaque, def_id)),
2764 ty::Generator(def_id, ..) => {
2765 Some((Self::Generator(tcx.generator_kind(def_id).unwrap()), def_id))
2767 ty::Foreign(def_id) => Some((Self::Foreign, def_id)),