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 basis of the system are the "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};
51 use crate::infer::{self, SuppressRegionErrors};
54 use crate::hir::def_id::DefId;
56 use crate::infer::opaque_types;
57 use crate::middle::region;
58 use crate::traits::{IfExpressionCause, MatchExpressionArmCause, ObligationCause};
59 use crate::traits::{ObligationCauseCode};
60 use crate::ty::error::TypeError;
61 use crate::ty::{self, subst::{Subst, SubstsRef}, Region, Ty, TyCtxt, TypeFoldable};
62 use errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString};
64 use syntax_pos::{Pos, Span};
70 pub mod nice_region_error;
72 impl<'tcx> TyCtxt<'tcx> {
73 pub fn note_and_explain_region(
75 region_scope_tree: ®ion::ScopeTree,
76 err: &mut DiagnosticBuilder<'_>,
78 region: ty::Region<'tcx>,
81 let (description, span) = match *region {
82 ty::ReScope(scope) => {
84 let unknown_scope = || {
86 "{}unknown scope: {:?}{}. Please report a bug.",
90 let span = scope.span(self, region_scope_tree);
91 let tag = match self.hir().find(scope.hir_id(region_scope_tree)) {
92 Some(Node::Block(_)) => "block",
93 Some(Node::Expr(expr)) => match expr.kind {
94 hir::ExprKind::Call(..) => "call",
95 hir::ExprKind::MethodCall(..) => "method call",
96 hir::ExprKind::Match(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
97 hir::ExprKind::Match(.., hir::MatchSource::WhileLetDesugar) => "while let",
98 hir::ExprKind::Match(.., hir::MatchSource::ForLoopDesugar) => "for",
99 hir::ExprKind::Match(..) => "match",
102 Some(Node::Stmt(_)) => "statement",
103 Some(Node::Item(it)) => Self::item_scope_tag(&it),
104 Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
105 Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
107 err.span_note(span, &unknown_scope());
111 let scope_decorated_tag = match scope.data {
112 region::ScopeData::Node => tag,
113 region::ScopeData::CallSite => "scope of call-site for function",
114 region::ScopeData::Arguments => "scope of function body",
115 region::ScopeData::Destruction => {
116 new_string = format!("destruction scope surrounding {}", tag);
119 region::ScopeData::Remainder(first_statement_index) => {
120 new_string = format!(
121 "block suffix following statement {}",
122 first_statement_index.index()
127 self.explain_span(scope_decorated_tag, span)
130 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
131 self.msg_span_from_free_region(region)
134 ty::ReEmpty => ("the empty lifetime".to_owned(), None),
136 ty::RePlaceholder(_) => (format!("any other region"), None),
138 // FIXME(#13998) RePlaceholder should probably print like
139 // ReFree rather than dumping Debug output on the user.
141 // We shouldn't really be having unification failures with ReVar
142 // and ReLateBound though.
143 ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
144 (format!("lifetime {:?}", region), None)
147 // We shouldn't encounter an error message with ReClosureBound.
148 ty::ReClosureBound(..) => {
149 bug!("encountered unexpected ReClosureBound: {:?}", region,);
153 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
156 pub fn note_and_explain_free_region(
158 err: &mut DiagnosticBuilder<'_>,
160 region: ty::Region<'tcx>,
163 let (description, span) = self.msg_span_from_free_region(region);
165 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
168 fn msg_span_from_free_region(self, region: ty::Region<'tcx>) -> (String, Option<Span>) {
170 ty::ReEarlyBound(_) | ty::ReFree(_) => {
171 self.msg_span_from_early_bound_and_free_regions(region)
173 ty::ReStatic => ("the static lifetime".to_owned(), None),
174 ty::ReEmpty => ("an empty lifetime".to_owned(), None),
175 _ => bug!("{:?}", region),
179 fn msg_span_from_early_bound_and_free_regions(
181 region: ty::Region<'tcx>,
182 ) -> (String, Option<Span>) {
183 let cm = self.sess.source_map();
185 let scope = region.free_region_binding_scope(self);
186 let node = self.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
187 let tag = match self.hir().find(node) {
188 Some(Node::Block(_)) | Some(Node::Expr(_)) => "body",
189 Some(Node::Item(it)) => Self::item_scope_tag(&it),
190 Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
191 Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
194 let (prefix, span) = match *region {
195 ty::ReEarlyBound(ref br) => {
196 let mut sp = cm.def_span(self.hir().span(node));
197 if let Some(param) = self.hir()
199 .and_then(|generics| generics.get_named(br.name))
203 (format!("the lifetime {} as defined on", br.name), sp)
205 ty::ReFree(ty::FreeRegion {
206 bound_region: ty::BoundRegion::BrNamed(_, name),
209 let mut sp = cm.def_span(self.hir().span(node));
210 if let Some(param) = self.hir()
212 .and_then(|generics| generics.get_named(name))
216 (format!("the lifetime {} as defined on", name), sp)
218 ty::ReFree(ref fr) => match fr.bound_region {
220 format!("the anonymous lifetime #{} defined on", idx + 1),
221 self.hir().span(node),
224 format!("the lifetime {} as defined on", region),
225 cm.def_span(self.hir().span(node)),
230 let (msg, opt_span) = self.explain_span(tag, span);
231 (format!("{} {}", prefix, msg), opt_span)
235 err: &mut DiagnosticBuilder<'_>,
241 let message = format!("{}{}{}", prefix, description, suffix);
243 if let Some(span) = span {
244 err.span_note(span, &message);
250 fn item_scope_tag(item: &hir::Item) -> &'static str {
252 hir::ItemKind::Impl(..) => "impl",
253 hir::ItemKind::Struct(..) => "struct",
254 hir::ItemKind::Union(..) => "union",
255 hir::ItemKind::Enum(..) => "enum",
256 hir::ItemKind::Trait(..) => "trait",
257 hir::ItemKind::Fn(..) => "function body",
262 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
264 hir::TraitItemKind::Method(..) => "method body",
265 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
269 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
271 hir::ImplItemKind::Method(..) => "method body",
272 hir::ImplItemKind::Const(..)
273 | hir::ImplItemKind::OpaqueTy(..)
274 | hir::ImplItemKind::TyAlias(..) => "associated item",
278 fn explain_span(self, heading: &str, span: Span) -> (String, Option<Span>) {
279 let lo = self.sess.source_map().lookup_char_pos(span.lo());
281 format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
287 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
288 pub fn report_region_errors(
290 region_scope_tree: ®ion::ScopeTree,
291 errors: &Vec<RegionResolutionError<'tcx>>,
292 suppress: SuppressRegionErrors,
295 "report_region_errors(): {} errors to start, suppress = {:?}",
300 if suppress.suppressed() {
304 // try to pre-process the errors, which will group some of them
305 // together into a `ProcessedErrors` group:
306 let errors = self.process_errors(errors);
309 "report_region_errors: {} errors after preprocessing",
313 for error in errors {
314 debug!("report_region_errors: error = {:?}", error);
316 if !self.try_report_nice_region_error(&error) {
317 match error.clone() {
318 // These errors could indicate all manner of different
319 // problems with many different solutions. Rather
320 // than generate a "one size fits all" error, what we
321 // attempt to do is go through a number of specific
322 // scenarios and try to find the best way to present
323 // the error. If all of these fails, we fall back to a rather
324 // general bit of code that displays the error information
325 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
326 if sub.is_placeholder() || sup.is_placeholder() {
327 self.report_placeholder_failure(region_scope_tree, origin, sub, sup)
330 self.report_concrete_failure(region_scope_tree, origin, sub, sup)
335 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
336 self.report_generic_bound_failure(
345 RegionResolutionError::SubSupConflict(
353 if sub_r.is_placeholder() {
354 self.report_placeholder_failure(
361 } else if sup_r.is_placeholder() {
362 self.report_placeholder_failure(
370 self.report_sub_sup_conflict(
381 RegionResolutionError::MemberConstraintFailure {
388 let hidden_ty = self.resolve_vars_if_possible(&hidden_ty);
389 opaque_types::unexpected_hidden_region_diagnostic(
391 Some(region_scope_tree),
402 // This method goes through all the errors and try to group certain types
403 // of error together, for the purpose of suggesting explicit lifetime
404 // parameters to the user. This is done so that we can have a more
405 // complete view of what lifetimes should be the same.
406 // If the return value is an empty vector, it means that processing
407 // failed (so the return value of this method should not be used).
409 // The method also attempts to weed out messages that seem like
410 // duplicates that will be unhelpful to the end-user. But
411 // obviously it never weeds out ALL errors.
414 errors: &Vec<RegionResolutionError<'tcx>>,
415 ) -> Vec<RegionResolutionError<'tcx>> {
416 debug!("process_errors()");
418 // We want to avoid reporting generic-bound failures if we can
419 // avoid it: these have a very high rate of being unhelpful in
420 // practice. This is because they are basically secondary
421 // checks that test the state of the region graph after the
422 // rest of inference is done, and the other kinds of errors
423 // indicate that the region constraint graph is internally
424 // inconsistent, so these test results are likely to be
427 // Therefore, we filter them out of the list unless they are
428 // the only thing in the list.
430 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
431 RegionResolutionError::GenericBoundFailure(..) => true,
432 RegionResolutionError::ConcreteFailure(..)
433 | RegionResolutionError::SubSupConflict(..)
434 | RegionResolutionError::MemberConstraintFailure { .. } => false,
437 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
442 .filter(|&e| !is_bound_failure(e))
447 // sort the errors by span, for better error message stability.
448 errors.sort_by_key(|u| match *u {
449 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
450 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
451 RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _) => rvo.span(),
452 RegionResolutionError::MemberConstraintFailure { span, .. } => span,
457 /// Adds a note if the types come from similarly named crates
458 fn check_and_note_conflicting_crates(
460 err: &mut DiagnosticBuilder<'_>,
461 terr: &TypeError<'tcx>,
464 use hir::def_id::CrateNum;
465 use hir::map::DisambiguatedDefPathData;
466 use ty::print::Printer;
467 use ty::subst::GenericArg;
469 struct AbsolutePathPrinter<'tcx> {
473 struct NonTrivialPath;
475 impl<'tcx> Printer<'tcx> for AbsolutePathPrinter<'tcx> {
476 type Error = NonTrivialPath;
478 type Path = Vec<String>;
481 type DynExistential = !;
484 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
490 _region: ty::Region<'_>,
491 ) -> Result<Self::Region, Self::Error> {
498 ) -> Result<Self::Type, Self::Error> {
502 fn print_dyn_existential(
504 _predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
505 ) -> Result<Self::DynExistential, Self::Error> {
511 _ct: &'tcx ty::Const<'tcx>,
512 ) -> Result<Self::Const, Self::Error> {
519 ) -> Result<Self::Path, Self::Error> {
520 Ok(vec![self.tcx.original_crate_name(cnum).to_string()])
525 _trait_ref: Option<ty::TraitRef<'tcx>>,
526 ) -> Result<Self::Path, Self::Error> {
532 _print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
533 _disambiguated_data: &DisambiguatedDefPathData,
535 _trait_ref: Option<ty::TraitRef<'tcx>>,
536 ) -> Result<Self::Path, Self::Error> {
541 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
542 disambiguated_data: &DisambiguatedDefPathData,
543 ) -> Result<Self::Path, Self::Error> {
544 let mut path = print_prefix(self)?;
545 path.push(disambiguated_data.data.as_interned_str().to_string());
548 fn path_generic_args(
550 print_prefix: impl FnOnce(Self) -> Result<Self::Path, Self::Error>,
551 _args: &[GenericArg<'tcx>],
552 ) -> Result<Self::Path, Self::Error> {
557 let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
558 // Only external crates, if either is from a local
559 // module we could have false positives
560 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
561 let abs_path = |def_id| {
562 AbsolutePathPrinter { tcx: self.tcx }
563 .print_def_path(def_id, &[])
566 // We compare strings because DefPath can be different
567 // for imported and non-imported crates
568 let same_path = || -> Result<_, NonTrivialPath> {
570 self.tcx.def_path_str(did1) == self.tcx.def_path_str(did2) ||
571 abs_path(did1)? == abs_path(did2)?
574 if same_path().unwrap_or(false) {
575 let crate_name = self.tcx.crate_name(did1.krate);
579 "Perhaps two different versions \
580 of crate `{}` are being used?",
588 TypeError::Sorts(ref exp_found) => {
589 // if they are both "path types", there's a chance of ambiguity
590 // due to different versions of the same crate
591 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _))
592 = (&exp_found.expected.kind, &exp_found.found.kind)
594 report_path_match(err, exp_adt.did, found_adt.did);
597 TypeError::Traits(ref exp_found) => {
598 report_path_match(err, exp_found.expected, exp_found.found);
600 _ => (), // FIXME(#22750) handle traits and stuff
604 fn note_error_origin(
606 err: &mut DiagnosticBuilder<'tcx>,
607 cause: &ObligationCause<'tcx>,
608 exp_found: Option<ty::error::ExpectedFound<Ty<'tcx>>>,
611 ObligationCauseCode::MatchExpressionArmPattern { span, ty } => {
612 if ty.is_suggestable() { // don't show type `_`
613 err.span_label(span, format!("this match expression has type `{}`", ty));
615 if let Some(ty::error::ExpectedFound { found, .. }) = exp_found {
616 if ty.is_box() && ty.boxed_ty() == found {
617 if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
620 "consider dereferencing the boxed value",
621 format!("*{}", snippet),
622 Applicability::MachineApplicable,
628 ObligationCauseCode::MatchExpressionArm(box MatchExpressionArmCause {
635 hir::MatchSource::IfLetDesugar { .. } => {
636 let msg = "`if let` arms have incompatible types";
637 err.span_label(cause.span, msg);
639 hir::MatchSource::TryDesugar => {
640 if let Some(ty::error::ExpectedFound { expected, .. }) = exp_found {
641 let discrim_expr = self.tcx.hir().expect_expr(discrim_hir_id);
642 let discrim_ty = if let hir::ExprKind::Call(_, args) = &discrim_expr.kind {
643 let arg_expr = args.first().expect("try desugaring call w/out arg");
644 self.in_progress_tables.and_then(|tables| {
645 tables.borrow().expr_ty_opt(arg_expr)
648 bug!("try desugaring w/out call expr as discriminant");
652 Some(ty) if expected == ty => {
653 let source_map = self.tcx.sess.source_map();
655 source_map.end_point(cause.span),
656 "try removing this `?`",
658 Applicability::MachineApplicable,
666 // `last_ty` can be `!`, `expected` will have better info when present.
667 let t = self.resolve_vars_if_possible(&match exp_found {
668 Some(ty::error::ExpectedFound { expected, .. }) => expected,
671 let msg = "`match` arms have incompatible types";
672 err.span_label(cause.span, msg);
673 if prior_arms.len() <= 4 {
674 for sp in prior_arms {
675 err.span_label( *sp, format!("this is found to be of type `{}`", t));
677 } else if let Some(sp) = prior_arms.last() {
680 format!("this and all prior arms are found to be of type `{}`", t),
685 ObligationCauseCode::IfExpression(box IfExpressionCause { then, outer, semicolon }) => {
686 err.span_label(then, "expected because of this");
687 outer.map(|sp| err.span_label(sp, "if and else have incompatible types"));
688 if let Some(sp) = semicolon {
689 err.span_suggestion_short(
691 "consider removing this semicolon",
693 Applicability::MachineApplicable,
701 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
702 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
703 /// populate `other_value` with `other_ty`.
707 /// ^^^^--------^ this is highlighted
709 /// | this type argument is exactly the same as the other type, not highlighted
710 /// this is highlighted
712 /// -------- this type is the same as a type argument in the other type, not highlighted
716 value: &mut DiagnosticStyledString,
717 other_value: &mut DiagnosticStyledString,
719 sub: ty::subst::SubstsRef<'tcx>,
723 // `value` and `other_value` hold two incomplete type representation for display.
724 // `name` is the path of both types being compared. `sub`
725 value.push_highlighted(name);
728 value.push_highlighted("<");
731 // Output the lifetimes for the first type
732 let lifetimes = sub.regions()
734 let s = lifetime.to_string();
743 if !lifetimes.is_empty() {
744 if sub.regions().count() < len {
745 value.push_normal(lifetimes + &", ");
747 value.push_normal(lifetimes);
751 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
752 // `pos` and `other_ty`.
753 for (i, type_arg) in sub.types().enumerate() {
755 let values = self.cmp(type_arg, other_ty);
756 value.0.extend((values.0).0);
757 other_value.0.extend((values.1).0);
759 value.push_highlighted(type_arg.to_string());
762 if len > 0 && i != len - 1 {
763 value.push_normal(", ");
765 //self.push_comma(&mut value, &mut other_value, len, i);
768 value.push_highlighted(">");
772 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
773 /// as that is the difference to the other type.
775 /// For the following code:
778 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
781 /// The type error output will behave in the following way:
785 /// ^^^^--------^ this is highlighted
787 /// | this type argument is exactly the same as the other type, not highlighted
788 /// this is highlighted
790 /// -------- this type is the same as a type argument in the other type, not highlighted
794 mut t1_out: &mut DiagnosticStyledString,
795 mut t2_out: &mut DiagnosticStyledString,
797 sub: ty::subst::SubstsRef<'tcx>,
801 for (i, ta) in sub.types().enumerate() {
803 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
806 if let &ty::Adt(def, _) = &ta.kind {
807 let path_ = self.tcx.def_path_str(def.did.clone());
808 if path_ == other_path {
809 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
817 /// Adds a `,` to the type representation only if it is appropriate.
820 value: &mut DiagnosticStyledString,
821 other_value: &mut DiagnosticStyledString,
825 if len > 0 && pos != len - 1 {
826 value.push_normal(", ");
827 other_value.push_normal(", ");
831 /// For generic types with parameters with defaults, remove the parameters corresponding to
832 /// the defaults. This repeats a lot of the logic found in `ty::print::pretty`.
833 fn strip_generic_default_params(
836 substs: ty::subst::SubstsRef<'tcx>,
837 ) -> SubstsRef<'tcx> {
838 let generics = self.tcx.generics_of(def_id);
839 let mut num_supplied_defaults = 0;
840 let mut type_params = generics.params.iter().rev().filter_map(|param| match param.kind {
841 ty::GenericParamDefKind::Lifetime => None,
842 ty::GenericParamDefKind::Type { has_default, .. } => Some((param.def_id, has_default)),
843 ty::GenericParamDefKind::Const => None, // FIXME(const_generics:defaults)
846 let has_default = type_params.peek().map(|(_, has_default)| has_default);
847 *has_default.unwrap_or(&false)
850 let types = substs.types().rev();
851 for ((def_id, has_default), actual) in type_params.zip(types) {
855 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
858 num_supplied_defaults += 1;
861 let len = generics.params.len();
862 let mut generics = generics.clone();
863 generics.params.truncate(len - num_supplied_defaults);
864 substs.truncate_to(self.tcx, &generics)
867 /// Compares two given types, eliding parts that are the same between them and highlighting
868 /// relevant differences, and return two representation of those types for highlighted printing.
869 fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
870 fn equals<'tcx>(a: Ty<'tcx>, b: Ty<'tcx>) -> bool {
871 match (&a.kind, &b.kind) {
872 (a, b) if *a == *b => true,
873 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
874 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_))
875 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Infer(ty::InferTy::IntVar(_)))
876 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
877 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Float(_))
878 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Infer(ty::InferTy::FloatVar(_))) => {
885 fn push_ty_ref<'tcx>(
886 r: &ty::Region<'tcx>,
888 mutbl: hir::Mutability,
889 s: &mut DiagnosticStyledString,
891 let mut r = r.to_string();
897 s.push_highlighted(format!(
900 if mutbl == hir::MutMutable { "mut " } else { "" }
902 s.push_normal(ty.to_string());
905 match (&t1.kind, &t2.kind) {
906 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
907 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
908 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
909 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
910 let path1 = self.tcx.def_path_str(def1.did.clone());
911 let path2 = self.tcx.def_path_str(def2.did.clone());
912 if def1.did == def2.did {
913 // Easy case. Replace same types with `_` to shorten the output and highlight
914 // the differing ones.
915 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
918 // --- ^ type argument elided
920 // highlighted in output
921 values.0.push_normal(path1);
922 values.1.push_normal(path2);
924 // Avoid printing out default generic parameters that are common to both
926 let len1 = sub_no_defaults_1.len();
927 let len2 = sub_no_defaults_2.len();
928 let common_len = cmp::min(len1, len2);
929 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
930 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
931 let common_default_params = remainder1
934 .zip(remainder2.iter().rev())
935 .filter(|(a, b)| a == b)
937 let len = sub1.len() - common_default_params;
939 // Only draw `<...>` if there're lifetime/type arguments.
941 values.0.push_normal("<");
942 values.1.push_normal("<");
945 fn lifetime_display(lifetime: Region<'_>) -> String {
946 let s = lifetime.to_string();
953 // At one point we'd like to elide all lifetimes here, they are irrelevant for
954 // all diagnostics that use this output
958 // ^^ ^^ --- type arguments are not elided
960 // | elided as they were the same
961 // not elided, they were different, but irrelevant
962 let lifetimes = sub1.regions().zip(sub2.regions());
963 for (i, lifetimes) in lifetimes.enumerate() {
964 let l1 = lifetime_display(lifetimes.0);
965 let l2 = lifetime_display(lifetimes.1);
967 values.0.push_normal("'_");
968 values.1.push_normal("'_");
970 values.0.push_highlighted(l1);
971 values.1.push_highlighted(l2);
973 self.push_comma(&mut values.0, &mut values.1, len, i);
976 // We're comparing two types with the same path, so we compare the type
977 // arguments for both. If they are the same, do not highlight and elide from the
981 // ^ elided type as this type argument was the same in both sides
982 let type_arguments = sub1.types().zip(sub2.types());
983 let regions_len = sub1.regions().count();
984 for (i, (ta1, ta2)) in type_arguments.take(len).enumerate() {
985 let i = i + regions_len;
987 values.0.push_normal("_");
988 values.1.push_normal("_");
990 let (x1, x2) = self.cmp(ta1, ta2);
991 (values.0).0.extend(x1.0);
992 (values.1).0.extend(x2.0);
994 self.push_comma(&mut values.0, &mut values.1, len, i);
997 // Close the type argument bracket.
998 // Only draw `<...>` if there're lifetime/type arguments.
1000 values.0.push_normal(">");
1001 values.1.push_normal(">");
1006 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
1008 // ------- this type argument is exactly the same as the other type
1010 if self.cmp_type_arg(
1022 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
1025 // ------- this type argument is exactly the same as the other type
1026 if self.cmp_type_arg(
1038 // We couldn't find anything in common, highlight everything.
1039 // let x: Bar<Qux> = y::<Foo<Zar>>();
1041 DiagnosticStyledString::highlighted(t1.to_string()),
1042 DiagnosticStyledString::highlighted(t2.to_string()),
1047 // When finding T != &T, highlight only the borrow
1048 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
1049 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1050 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1051 values.1.push_normal(t2.to_string());
1054 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
1055 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1056 values.0.push_normal(t1.to_string());
1057 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1061 // When encountering &T != &mut T, highlight only the borrow
1062 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
1063 if equals(&ref_ty1, &ref_ty2) =>
1065 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
1066 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
1067 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
1073 // The two types are the same, elide and don't highlight.
1075 DiagnosticStyledString::normal("_"),
1076 DiagnosticStyledString::normal("_"),
1079 // We couldn't find anything in common, highlight everything.
1081 DiagnosticStyledString::highlighted(t1.to_string()),
1082 DiagnosticStyledString::highlighted(t2.to_string()),
1089 pub fn note_type_err(
1091 diag: &mut DiagnosticBuilder<'tcx>,
1092 cause: &ObligationCause<'tcx>,
1093 secondary_span: Option<(Span, String)>,
1094 mut values: Option<ValuePairs<'tcx>>,
1095 terr: &TypeError<'tcx>,
1097 // For some types of errors, expected-found does not make
1098 // sense, so just ignore the values we were given.
1100 TypeError::CyclicTy(_) => {
1106 let (expected_found, exp_found, is_simple_error) = match values {
1107 None => (None, None, false),
1109 let (is_simple_error, exp_found) = match values {
1110 ValuePairs::Types(exp_found) => {
1112 exp_found.expected.is_primitive() && exp_found.found.is_primitive();
1114 (is_simple_err, Some(exp_found))
1118 let vals = match self.values_str(&values) {
1119 Some((expected, found)) => Some((expected, found)),
1121 // Derived error. Cancel the emitter.
1126 (vals, exp_found, is_simple_error)
1130 let span = cause.span(self.tcx);
1132 diag.span_label(span, terr.to_string());
1133 if let Some((sp, msg)) = secondary_span {
1134 diag.span_label(sp, msg);
1137 if let Some((expected, found)) = expected_found {
1138 match (terr, is_simple_error, expected == found) {
1139 (&TypeError::Sorts(ref values), false, true) => {
1140 let sort_string = | a_type: Ty<'tcx> |
1141 if let ty::Opaque(def_id, _) = a_type.kind {
1142 format!(" (opaque type at {})", self.tcx.sess.source_map()
1143 .mk_substr_filename(self.tcx.def_span(def_id)))
1145 format!(" ({})", a_type.sort_string(self.tcx))
1147 diag.note_expected_found_extra(
1151 &sort_string(values.expected),
1152 &sort_string(values.found),
1156 if let Some(exp_found) = exp_found {
1157 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
1160 diag.note_expected_found(&"type", expected, found);
1166 self.check_and_note_conflicting_crates(diag, terr, span);
1167 self.tcx.note_and_explain_type_err(diag, terr, span);
1169 // It reads better to have the error origin as the final
1171 self.note_error_origin(diag, &cause, exp_found);
1174 /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1176 fn suggest_as_ref_where_appropriate(
1179 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1180 diag: &mut DiagnosticBuilder<'tcx>,
1182 match (&exp_found.expected.kind, &exp_found.found.kind) {
1183 (ty::Adt(exp_def, exp_substs), ty::Ref(_, found_ty, _)) => {
1184 if let ty::Adt(found_def, found_substs) = found_ty.kind {
1185 let path_str = format!("{:?}", exp_def);
1186 if exp_def == &found_def {
1187 let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1189 let result_msg = "you can convert from `&Result<T, E>` to \
1190 `Result<&T, &E>` using `.as_ref()`";
1191 let have_as_ref = &[
1192 ("std::option::Option", opt_msg),
1193 ("core::option::Option", opt_msg),
1194 ("std::result::Result", result_msg),
1195 ("core::result::Result", result_msg),
1197 if let Some(msg) = have_as_ref.iter()
1198 .filter_map(|(path, msg)| if &path_str == path {
1204 let mut show_suggestion = true;
1205 for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1207 ty::Ref(_, exp_ty, _) => {
1208 match (&exp_ty.kind, &found_ty.kind) {
1212 (ty::Infer(_), _) => {}
1213 _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1214 _ => show_suggestion = false,
1217 ty::Param(_) | ty::Infer(_) => {}
1218 _ => show_suggestion = false,
1221 if let (Ok(snippet), true) = (
1222 self.tcx.sess.source_map().span_to_snippet(span),
1225 diag.span_suggestion(
1228 format!("{}.as_ref()", snippet),
1229 Applicability::MachineApplicable,
1240 pub fn report_and_explain_type_error(
1242 trace: TypeTrace<'tcx>,
1243 terr: &TypeError<'tcx>,
1244 ) -> DiagnosticBuilder<'tcx> {
1246 "report_and_explain_type_error(trace={:?}, terr={:?})",
1250 let span = trace.cause.span(self.tcx);
1251 let failure_code = trace.cause.as_failure_code(terr);
1252 let mut diag = match failure_code {
1253 FailureCode::Error0317(failure_str) => {
1254 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1256 FailureCode::Error0580(failure_str) => {
1257 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1259 FailureCode::Error0308(failure_str) => {
1260 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1262 FailureCode::Error0644(failure_str) => {
1263 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1266 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1272 values: &ValuePairs<'tcx>,
1273 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1275 infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1276 infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1277 infer::Consts(ref exp_found) => self.expected_found_str(exp_found),
1278 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1279 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1283 fn expected_found_str_ty(
1285 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1286 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1287 let exp_found = self.resolve_vars_if_possible(exp_found);
1288 if exp_found.references_error() {
1292 Some(self.cmp(exp_found.expected, exp_found.found))
1295 /// Returns a string of the form "expected `{}`, found `{}`".
1296 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1298 exp_found: &ty::error::ExpectedFound<T>,
1299 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1300 let exp_found = self.resolve_vars_if_possible(exp_found);
1301 if exp_found.references_error() {
1306 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1307 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1311 pub fn report_generic_bound_failure(
1313 region_scope_tree: ®ion::ScopeTree,
1315 origin: Option<SubregionOrigin<'tcx>>,
1316 bound_kind: GenericKind<'tcx>,
1319 self.construct_generic_bound_failure(region_scope_tree, span, origin, bound_kind, sub)
1323 pub fn construct_generic_bound_failure(
1325 region_scope_tree: ®ion::ScopeTree,
1327 origin: Option<SubregionOrigin<'tcx>>,
1328 bound_kind: GenericKind<'tcx>,
1330 ) -> DiagnosticBuilder<'a> {
1331 // Attempt to obtain the span of the parameter so we can
1332 // suggest adding an explicit lifetime bound to it.
1333 let type_param_span = match (self.in_progress_tables, bound_kind) {
1334 (Some(ref table), GenericKind::Param(ref param)) => {
1335 let table = table.borrow();
1336 table.local_id_root.and_then(|did| {
1337 let generics = self.tcx.generics_of(did);
1338 // Account for the case where `did` corresponds to `Self`, which doesn't have
1339 // the expected type argument.
1340 if !(generics.has_self && param.index == 0) {
1341 let type_param = generics.type_param(param, self.tcx);
1342 let hir = &self.tcx.hir();
1343 hir.as_local_hir_id(type_param.def_id).map(|id| {
1344 // Get the `hir::Param` to verify whether it already has any bounds.
1345 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1346 // instead we suggest `T: 'a + 'b` in that case.
1347 let mut has_bounds = false;
1348 if let Node::GenericParam(param) = hir.get(id) {
1349 has_bounds = !param.bounds.is_empty();
1351 let sp = hir.span(id);
1352 // `sp` only covers `T`, change it so that it covers
1353 // `T:` when appropriate
1354 let is_impl_trait = bound_kind.to_string().starts_with("impl ");
1355 let sp = if has_bounds && !is_impl_trait {
1359 .next_point(self.tcx.sess.source_map().next_point(sp)))
1363 (sp, has_bounds, is_impl_trait)
1373 let labeled_user_string = match bound_kind {
1374 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1375 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1378 if let Some(SubregionOrigin::CompareImplMethodObligation {
1385 return self.report_extra_impl_obligation(
1390 &format!("`{}: {}`", bound_kind, sub),
1394 fn binding_suggestion<'tcx, S: fmt::Display>(
1395 err: &mut DiagnosticBuilder<'tcx>,
1396 type_param_span: Option<(Span, bool, bool)>,
1397 bound_kind: GenericKind<'tcx>,
1400 let consider = format!(
1401 "consider adding an explicit lifetime bound {}",
1402 if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
1403 format!(" `{}` to `{}`...", sub, bound_kind)
1405 format!("`{}: {}`...", bound_kind, sub)
1408 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1409 let suggestion = if is_impl_trait {
1410 format!("{} + {}", bound_kind, sub)
1412 let tail = if has_lifetimes { " + " } else { "" };
1413 format!("{}: {}{}", bound_kind, sub, tail)
1415 err.span_suggestion_short(
1419 Applicability::MaybeIncorrect, // Issue #41966
1422 err.help(&consider);
1426 let mut err = match *sub {
1428 | ty::ReFree(ty::FreeRegion {
1429 bound_region: ty::BrNamed(..),
1432 // Does the required lifetime have a nice name we can print?
1433 let mut err = struct_span_err!(
1437 "{} may not live long enough",
1440 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1445 // Does the required lifetime have a nice name we can print?
1446 let mut err = struct_span_err!(
1450 "{} may not live long enough",
1453 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1458 // If not, be less specific.
1459 let mut err = struct_span_err!(
1463 "{} may not live long enough",
1467 "consider adding an explicit lifetime bound for `{}`",
1470 self.tcx.note_and_explain_region(
1473 &format!("{} must be valid for ", labeled_user_string),
1481 if let Some(origin) = origin {
1482 self.note_region_origin(&mut err, &origin);
1487 fn report_sub_sup_conflict(
1489 region_scope_tree: ®ion::ScopeTree,
1490 var_origin: RegionVariableOrigin,
1491 sub_origin: SubregionOrigin<'tcx>,
1492 sub_region: Region<'tcx>,
1493 sup_origin: SubregionOrigin<'tcx>,
1494 sup_region: Region<'tcx>,
1496 let mut err = self.report_inference_failure(var_origin);
1498 self.tcx.note_and_explain_region(
1501 "first, the lifetime cannot outlive ",
1506 match (&sup_origin, &sub_origin) {
1507 (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1508 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
1509 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
1510 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
1511 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
1512 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
1513 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
1514 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
1515 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
1516 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
1518 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1519 self.values_str(&sup_trace.values),
1520 self.values_str(&sub_trace.values),
1522 if sub_expected == sup_expected && sub_found == sup_found {
1523 self.tcx.note_and_explain_region(
1526 "...but the lifetime must also be valid for ",
1531 "...so that the {}:\nexpected {}\n found {}",
1532 sup_trace.cause.as_requirement_str(),
1533 sup_expected.content(),
1544 self.note_region_origin(&mut err, &sup_origin);
1546 self.tcx.note_and_explain_region(
1549 "but, the lifetime must be valid for ",
1554 self.note_region_origin(&mut err, &sub_origin);
1559 impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
1560 fn report_inference_failure(
1562 var_origin: RegionVariableOrigin,
1563 ) -> DiagnosticBuilder<'tcx> {
1564 let br_string = |br: ty::BoundRegion| {
1565 let mut s = match br {
1566 ty::BrNamed(_, name) => name.to_string(),
1574 let var_description = match var_origin {
1575 infer::MiscVariable(_) => String::new(),
1576 infer::PatternRegion(_) => " for pattern".to_string(),
1577 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1578 infer::Autoref(_) => " for autoref".to_string(),
1579 infer::Coercion(_) => " for automatic coercion".to_string(),
1580 infer::LateBoundRegion(_, br, infer::FnCall) => {
1581 format!(" for lifetime parameter {}in function call", br_string(br))
1583 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1584 format!(" for lifetime parameter {}in generic type", br_string(br))
1586 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1587 " for lifetime parameter {}in trait containing associated type `{}`",
1589 self.tcx.associated_item(def_id).ident
1591 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1592 infer::BoundRegionInCoherence(name) => {
1593 format!(" for lifetime parameter `{}` in coherence check", name)
1595 infer::UpvarRegion(ref upvar_id, _) => {
1596 let var_name = self.tcx.hir().name(upvar_id.var_path.hir_id);
1597 format!(" for capture of `{}` by closure", var_name)
1599 infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1606 "cannot infer an appropriate lifetime{} \
1607 due to conflicting requirements",
1614 Error0317(&'static str),
1615 Error0580(&'static str),
1616 Error0308(&'static str),
1617 Error0644(&'static str),
1620 impl<'tcx> ObligationCause<'tcx> {
1621 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1622 use self::FailureCode::*;
1623 use crate::traits::ObligationCauseCode::*;
1625 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1626 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) =>
1627 Error0308(match source {
1628 hir::MatchSource::IfLetDesugar { .. } =>
1629 "`if let` arms have incompatible types",
1630 hir::MatchSource::TryDesugar => {
1631 "try expression alternatives have incompatible types"
1633 _ => "match arms have incompatible types",
1635 IfExpression { .. } => Error0308("if and else have incompatible types"),
1636 IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1637 MainFunctionType => Error0580("main function has wrong type"),
1638 StartFunctionType => Error0308("start function has wrong type"),
1639 IntrinsicType => Error0308("intrinsic has wrong type"),
1640 MethodReceiver => Error0308("mismatched `self` parameter type"),
1642 // In the case where we have no more specific thing to
1643 // say, also take a look at the error code, maybe we can
1646 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1647 Error0644("closure/generator type that references itself")
1649 TypeError::IntrinsicCast => {
1650 Error0308("cannot coerce intrinsics to function pointers")
1652 _ => Error0308("mismatched types"),
1657 fn as_requirement_str(&self) -> &'static str {
1658 use crate::traits::ObligationCauseCode::*;
1660 CompareImplMethodObligation { .. } => "method type is compatible with trait",
1661 ExprAssignable => "expression is assignable",
1662 MatchExpressionArm(box MatchExpressionArmCause { source, .. }) => match source {
1663 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1664 _ => "match arms have compatible types",
1666 IfExpression { .. } => "if and else have incompatible types",
1667 IfExpressionWithNoElse => "if missing an else returns ()",
1668 MainFunctionType => "`main` function has the correct type",
1669 StartFunctionType => "`start` function has the correct type",
1670 IntrinsicType => "intrinsic has the correct type",
1671 MethodReceiver => "method receiver has the correct type",
1672 _ => "types are compatible",