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 infer::{self, SuppressRegionErrors};
53 use errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString};
55 use hir::def_id::DefId;
59 use syntax::ast::DUMMY_NODE_ID;
60 use syntax_pos::{Pos, Span};
61 use traits::{ObligationCause, ObligationCauseCode};
62 use ty::error::TypeError;
63 use ty::{self, subst::Subst, Region, Ty, TyCtxt, TyKind, TypeFoldable};
69 pub mod nice_region_error;
71 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
72 pub fn note_and_explain_region(
74 region_scope_tree: ®ion::ScopeTree,
75 err: &mut DiagnosticBuilder<'_>,
77 region: ty::Region<'tcx>,
80 let (description, span) = match *region {
81 ty::ReScope(scope) => {
83 let unknown_scope = || {
85 "{}unknown scope: {:?}{}. Please report a bug.",
89 let span = scope.span(self, region_scope_tree);
90 let tag = match self.hir().find(scope.node_id(self, region_scope_tree)) {
91 Some(Node::Block(_)) => "block",
92 Some(Node::Expr(expr)) => match expr.node {
93 hir::ExprKind::Call(..) => "call",
94 hir::ExprKind::MethodCall(..) => "method call",
95 hir::ExprKind::Match(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
96 hir::ExprKind::Match(.., hir::MatchSource::WhileLetDesugar) => "while let",
97 hir::ExprKind::Match(.., hir::MatchSource::ForLoopDesugar) => "for",
98 hir::ExprKind::Match(..) => "match",
101 Some(Node::Stmt(_)) => "statement",
102 Some(Node::Item(it)) => Self::item_scope_tag(&it),
103 Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
104 Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
106 err.span_note(span, &unknown_scope());
110 let scope_decorated_tag = match scope.data {
111 region::ScopeData::Node => tag,
112 region::ScopeData::CallSite => "scope of call-site for function",
113 region::ScopeData::Arguments => "scope of function body",
114 region::ScopeData::Destruction => {
115 new_string = format!("destruction scope surrounding {}", tag);
118 region::ScopeData::Remainder(first_statement_index) => {
119 new_string = format!(
120 "block suffix following statement {}",
121 first_statement_index.index()
126 self.explain_span(scope_decorated_tag, span)
129 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
130 self.msg_span_from_free_region(region)
133 ty::ReEmpty => ("the empty lifetime".to_owned(), None),
135 // FIXME(#13998) RePlaceholder should probably print like
136 // ReFree rather than dumping Debug output on the user.
138 // We shouldn't really be having unification failures with ReVar
139 // and ReLateBound though.
140 ty::RePlaceholder(..) | ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
141 (format!("lifetime {:?}", region), None)
144 // We shouldn't encounter an error message with ReClosureBound.
145 ty::ReClosureBound(..) => {
146 bug!("encountered unexpected ReClosureBound: {:?}", region,);
150 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
153 pub fn note_and_explain_free_region(
155 err: &mut DiagnosticBuilder<'_>,
157 region: ty::Region<'tcx>,
160 let (description, span) = self.msg_span_from_free_region(region);
162 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
165 fn msg_span_from_free_region(self, region: ty::Region<'tcx>) -> (String, Option<Span>) {
167 ty::ReEarlyBound(_) | ty::ReFree(_) => {
168 self.msg_span_from_early_bound_and_free_regions(region)
170 ty::ReStatic => ("the static lifetime".to_owned(), None),
171 ty::ReEmpty => ("an empty lifetime".to_owned(), None),
172 _ => bug!("{:?}", region),
176 fn msg_span_from_early_bound_and_free_regions(
178 region: ty::Region<'tcx>,
179 ) -> (String, Option<Span>) {
180 let cm = self.sess.source_map();
182 let scope = region.free_region_binding_scope(self);
183 let node = self.hir().as_local_node_id(scope).unwrap_or(DUMMY_NODE_ID);
184 let tag = match self.hir().find(node) {
185 Some(Node::Block(_)) | Some(Node::Expr(_)) => "body",
186 Some(Node::Item(it)) => Self::item_scope_tag(&it),
187 Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
188 Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
191 let (prefix, span) = match *region {
192 ty::ReEarlyBound(ref br) => {
193 let mut sp = cm.def_span(self.hir().span(node));
194 if let Some(param) = self.hir()
196 .and_then(|generics| generics.get_named(&br.name))
200 (format!("the lifetime {} as defined on", br.name), sp)
202 ty::ReFree(ty::FreeRegion {
203 bound_region: ty::BoundRegion::BrNamed(_, ref name),
206 let mut sp = cm.def_span(self.hir().span(node));
207 if let Some(param) = self.hir()
209 .and_then(|generics| generics.get_named(&name))
213 (format!("the lifetime {} as defined on", name), sp)
215 ty::ReFree(ref fr) => match fr.bound_region {
217 format!("the anonymous lifetime #{} defined on", idx + 1),
218 self.hir().span(node),
221 "an anonymous lifetime defined on".to_owned(),
222 self.hir().span(node),
225 format!("the lifetime {} as defined on", fr.bound_region),
226 cm.def_span(self.hir().span(node)),
231 let (msg, opt_span) = self.explain_span(tag, span);
232 (format!("{} {}", prefix, msg), opt_span)
236 err: &mut DiagnosticBuilder<'_>,
242 let message = format!("{}{}{}", prefix, description, suffix);
244 if let Some(span) = span {
245 err.span_note(span, &message);
251 fn item_scope_tag(item: &hir::Item) -> &'static str {
253 hir::ItemKind::Impl(..) => "impl",
254 hir::ItemKind::Struct(..) => "struct",
255 hir::ItemKind::Union(..) => "union",
256 hir::ItemKind::Enum(..) => "enum",
257 hir::ItemKind::Trait(..) => "trait",
258 hir::ItemKind::Fn(..) => "function body",
263 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
265 hir::TraitItemKind::Method(..) => "method body",
266 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
270 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
272 hir::ImplItemKind::Method(..) => "method body",
273 hir::ImplItemKind::Const(..)
274 | hir::ImplItemKind::Existential(..)
275 | hir::ImplItemKind::Type(..) => "associated item",
279 fn explain_span(self, heading: &str, span: Span) -> (String, Option<Span>) {
280 let lo = self.sess.source_map().lookup_char_pos_adj(span.lo());
282 format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
288 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
289 pub fn report_region_errors(
291 region_scope_tree: ®ion::ScopeTree,
292 errors: &Vec<RegionResolutionError<'tcx>>,
293 suppress: SuppressRegionErrors,
296 "report_region_errors(): {} errors to start, suppress = {:?}",
301 if suppress.suppressed() {
305 // try to pre-process the errors, which will group some of them
306 // together into a `ProcessedErrors` group:
307 let errors = self.process_errors(errors);
310 "report_region_errors: {} errors after preprocessing",
314 for error in errors {
315 debug!("report_region_errors: error = {:?}", error);
317 if !self.try_report_nice_region_error(&error) {
318 match error.clone() {
319 // These errors could indicate all manner of different
320 // problems with many different solutions. Rather
321 // than generate a "one size fits all" error, what we
322 // attempt to do is go through a number of specific
323 // scenarios and try to find the best way to present
324 // the error. If all of these fails, we fall back to a rather
325 // general bit of code that displays the error information
326 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
327 self.report_concrete_failure(region_scope_tree, origin, sub, sup)
331 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
332 self.report_generic_bound_failure(
341 RegionResolutionError::SubSupConflict(
348 self.report_sub_sup_conflict(
362 // This method goes through all the errors and try to group certain types
363 // of error together, for the purpose of suggesting explicit lifetime
364 // parameters to the user. This is done so that we can have a more
365 // complete view of what lifetimes should be the same.
366 // If the return value is an empty vector, it means that processing
367 // failed (so the return value of this method should not be used).
369 // The method also attempts to weed out messages that seem like
370 // duplicates that will be unhelpful to the end-user. But
371 // obviously it never weeds out ALL errors.
374 errors: &Vec<RegionResolutionError<'tcx>>,
375 ) -> Vec<RegionResolutionError<'tcx>> {
376 debug!("process_errors()");
378 // We want to avoid reporting generic-bound failures if we can
379 // avoid it: these have a very high rate of being unhelpful in
380 // practice. This is because they are basically secondary
381 // checks that test the state of the region graph after the
382 // rest of inference is done, and the other kinds of errors
383 // indicate that the region constraint graph is internally
384 // inconsistent, so these test results are likely to be
387 // Therefore, we filter them out of the list unless they are
388 // the only thing in the list.
390 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
391 RegionResolutionError::GenericBoundFailure(..) => true,
392 RegionResolutionError::ConcreteFailure(..)
393 | RegionResolutionError::SubSupConflict(..) => false,
396 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
401 .filter(|&e| !is_bound_failure(e))
406 // sort the errors by span, for better error message stability.
407 errors.sort_by_key(|u| match *u {
408 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
409 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
410 RegionResolutionError::SubSupConflict(ref rvo, _, _, _, _) => rvo.span(),
415 /// Adds a note if the types come from similarly named crates
416 fn check_and_note_conflicting_crates(
418 err: &mut DiagnosticBuilder<'_>,
419 terr: &TypeError<'tcx>,
422 let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
423 // Only external crates, if either is from a local
424 // module we could have false positives
425 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
426 let exp_path = self.tcx.item_path_str(did1);
427 let found_path = self.tcx.item_path_str(did2);
428 let exp_abs_path = self.tcx.absolute_item_path_str(did1);
429 let found_abs_path = self.tcx.absolute_item_path_str(did2);
430 // We compare strings because DefPath can be different
431 // for imported and non-imported crates
432 if exp_path == found_path || exp_abs_path == found_abs_path {
433 let crate_name = self.tcx.crate_name(did1.krate);
437 "Perhaps two different versions \
438 of crate `{}` are being used?",
446 TypeError::Sorts(ref exp_found) => {
447 // if they are both "path types", there's a chance of ambiguity
448 // due to different versions of the same crate
449 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _))
450 = (&exp_found.expected.sty, &exp_found.found.sty)
452 report_path_match(err, exp_adt.did, found_adt.did);
455 TypeError::Traits(ref exp_found) => {
456 report_path_match(err, exp_found.expected, exp_found.found);
458 _ => (), // FIXME(#22750) handle traits and stuff
462 fn note_error_origin(&self, err: &mut DiagnosticBuilder<'tcx>, cause: &ObligationCause<'tcx>) {
464 ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
465 hir::MatchSource::IfLetDesugar { .. } => {
466 let msg = "`if let` arm with an incompatible type";
467 if self.tcx.sess.source_map().is_multiline(arm_span) {
468 err.span_note(arm_span, msg);
470 err.span_label(arm_span, msg);
473 hir::MatchSource::TryDesugar => {}
475 let msg = "match arm with an incompatible type";
476 if self.tcx.sess.source_map().is_multiline(arm_span) {
477 err.span_note(arm_span, msg);
479 err.span_label(arm_span, msg);
487 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
488 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
489 /// populate `other_value` with `other_ty`.
493 /// ^^^^--------^ this is highlighted
495 /// | this type argument is exactly the same as the other type, not highlighted
496 /// this is highlighted
498 /// -------- this type is the same as a type argument in the other type, not highlighted
502 value: &mut DiagnosticStyledString,
503 other_value: &mut DiagnosticStyledString,
505 sub: &ty::subst::Substs<'tcx>,
509 // `value` and `other_value` hold two incomplete type representation for display.
510 // `name` is the path of both types being compared. `sub`
511 value.push_highlighted(name);
514 value.push_highlighted("<");
517 // Output the lifetimes for the first type
518 let lifetimes = sub.regions()
520 let s = lifetime.to_string();
529 if !lifetimes.is_empty() {
530 if sub.regions().count() < len {
531 value.push_normal(lifetimes + &", ");
533 value.push_normal(lifetimes);
537 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
538 // `pos` and `other_ty`.
539 for (i, type_arg) in sub.types().enumerate() {
541 let values = self.cmp(type_arg, other_ty);
542 value.0.extend((values.0).0);
543 other_value.0.extend((values.1).0);
545 value.push_highlighted(type_arg.to_string());
548 if len > 0 && i != len - 1 {
549 value.push_normal(", ");
551 //self.push_comma(&mut value, &mut other_value, len, i);
554 value.push_highlighted(">");
558 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
559 /// as that is the difference to the other type.
561 /// For the following code:
564 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
567 /// The type error output will behave in the following way:
571 /// ^^^^--------^ this is highlighted
573 /// | this type argument is exactly the same as the other type, not highlighted
574 /// this is highlighted
576 /// -------- this type is the same as a type argument in the other type, not highlighted
580 mut t1_out: &mut DiagnosticStyledString,
581 mut t2_out: &mut DiagnosticStyledString,
583 sub: &ty::subst::Substs<'tcx>,
587 for (i, ta) in sub.types().enumerate() {
589 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
592 if let &ty::Adt(def, _) = &ta.sty {
593 let path_ = self.tcx.item_path_str(def.did.clone());
594 if path_ == other_path {
595 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
603 /// Add a `,` to the type representation only if it is appropriate.
606 value: &mut DiagnosticStyledString,
607 other_value: &mut DiagnosticStyledString,
611 if len > 0 && pos != len - 1 {
612 value.push_normal(", ");
613 other_value.push_normal(", ");
617 /// For generic types with parameters with defaults, remove the parameters corresponding to
618 /// the defaults. This repeats a lot of the logic found in `PrintContext::parameterized`.
619 fn strip_generic_default_params(
622 substs: &ty::subst::Substs<'tcx>,
623 ) -> &'tcx ty::subst::Substs<'tcx> {
624 let generics = self.tcx.generics_of(def_id);
625 let mut num_supplied_defaults = 0;
626 let mut type_params = generics
630 .filter_map(|param| match param.kind {
631 ty::GenericParamDefKind::Lifetime => None,
632 ty::GenericParamDefKind::Type { has_default, .. } => {
633 Some((param.def_id, has_default))
638 let has_default = type_params.peek().map(|(_, has_default)| has_default);
639 *has_default.unwrap_or(&false)
642 let types = substs.types().rev();
643 for ((def_id, has_default), actual) in type_params.zip(types) {
647 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
650 num_supplied_defaults += 1;
653 let len = generics.params.len();
654 let mut generics = generics.clone();
655 generics.params.truncate(len - num_supplied_defaults);
656 substs.truncate_to(self.tcx, &generics)
659 /// Compare two given types, eliding parts that are the same between them and highlighting
660 /// relevant differences, and return two representation of those types for highlighted printing.
661 fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
662 fn equals<'tcx>(a: &Ty<'tcx>, b: &Ty<'tcx>) -> bool {
663 match (&a.sty, &b.sty) {
664 (a, b) if *a == *b => true,
665 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
666 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_))
667 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Infer(ty::InferTy::IntVar(_)))
668 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
669 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Float(_))
670 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Infer(ty::InferTy::FloatVar(_))) => {
677 fn push_ty_ref<'tcx>(
678 r: &ty::Region<'tcx>,
680 mutbl: hir::Mutability,
681 s: &mut DiagnosticStyledString,
683 let r = &r.to_string();
684 s.push_highlighted(format!(
687 if r == "" { "" } else { " " },
688 if mutbl == hir::MutMutable { "mut " } else { "" }
690 s.push_normal(ty.to_string());
693 match (&t1.sty, &t2.sty) {
694 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
695 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
696 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
697 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
698 let path1 = self.tcx.item_path_str(def1.did.clone());
699 let path2 = self.tcx.item_path_str(def2.did.clone());
700 if def1.did == def2.did {
701 // Easy case. Replace same types with `_` to shorten the output and highlight
702 // the differing ones.
703 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
706 // --- ^ type argument elided
708 // highlighted in output
709 values.0.push_normal(path1);
710 values.1.push_normal(path2);
712 // Avoid printing out default generic parameters that are common to both
714 let len1 = sub_no_defaults_1.len();
715 let len2 = sub_no_defaults_2.len();
716 let common_len = cmp::min(len1, len2);
717 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
718 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
719 let common_default_params = remainder1
722 .zip(remainder2.iter().rev())
723 .filter(|(a, b)| a == b)
725 let len = sub1.len() - common_default_params;
727 // Only draw `<...>` if there're lifetime/type arguments.
729 values.0.push_normal("<");
730 values.1.push_normal("<");
733 fn lifetime_display(lifetime: Region<'_>) -> String {
734 let s = lifetime.to_string();
741 // At one point we'd like to elide all lifetimes here, they are irrelevant for
742 // all diagnostics that use this output
746 // ^^ ^^ --- type arguments are not elided
748 // | elided as they were the same
749 // not elided, they were different, but irrelevant
750 let lifetimes = sub1.regions().zip(sub2.regions());
751 for (i, lifetimes) in lifetimes.enumerate() {
752 let l1 = lifetime_display(lifetimes.0);
753 let l2 = lifetime_display(lifetimes.1);
755 values.0.push_normal("'_");
756 values.1.push_normal("'_");
758 values.0.push_highlighted(l1);
759 values.1.push_highlighted(l2);
761 self.push_comma(&mut values.0, &mut values.1, len, i);
764 // We're comparing two types with the same path, so we compare the type
765 // arguments for both. If they are the same, do not highlight and elide from the
769 // ^ elided type as this type argument was the same in both sides
770 let type_arguments = sub1.types().zip(sub2.types());
771 let regions_len = sub1.regions().count();
772 for (i, (ta1, ta2)) in type_arguments.take(len).enumerate() {
773 let i = i + regions_len;
775 values.0.push_normal("_");
776 values.1.push_normal("_");
778 let (x1, x2) = self.cmp(ta1, ta2);
779 (values.0).0.extend(x1.0);
780 (values.1).0.extend(x2.0);
782 self.push_comma(&mut values.0, &mut values.1, len, i);
785 // Close the type argument bracket.
786 // Only draw `<...>` if there're lifetime/type arguments.
788 values.0.push_normal(">");
789 values.1.push_normal(">");
794 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
796 // ------- this type argument is exactly the same as the other type
798 if self.cmp_type_arg(
810 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
813 // ------- this type argument is exactly the same as the other type
814 if self.cmp_type_arg(
826 // We couldn't find anything in common, highlight everything.
827 // let x: Bar<Qux> = y::<Foo<Zar>>();
829 DiagnosticStyledString::highlighted(t1.to_string()),
830 DiagnosticStyledString::highlighted(t2.to_string()),
835 // When finding T != &T, highlight only the borrow
836 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
837 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
838 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
839 values.1.push_normal(t2.to_string());
842 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
843 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
844 values.0.push_normal(t1.to_string());
845 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
849 // When encountering &T != &mut T, highlight only the borrow
850 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
851 if equals(&ref_ty1, &ref_ty2) =>
853 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
854 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
855 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
861 // The two types are the same, elide and don't highlight.
863 DiagnosticStyledString::normal("_"),
864 DiagnosticStyledString::normal("_"),
867 // We couldn't find anything in common, highlight everything.
869 DiagnosticStyledString::highlighted(t1.to_string()),
870 DiagnosticStyledString::highlighted(t2.to_string()),
877 pub fn note_type_err(
879 diag: &mut DiagnosticBuilder<'tcx>,
880 cause: &ObligationCause<'tcx>,
881 secondary_span: Option<(Span, String)>,
882 mut values: Option<ValuePairs<'tcx>>,
883 terr: &TypeError<'tcx>,
885 // For some types of errors, expected-found does not make
886 // sense, so just ignore the values we were given.
888 TypeError::CyclicTy(_) => {
894 let (expected_found, exp_found, is_simple_error) = match values {
895 None => (None, None, false),
897 let (is_simple_error, exp_found) = match values {
898 ValuePairs::Types(exp_found) => {
900 exp_found.expected.is_primitive() && exp_found.found.is_primitive();
902 (is_simple_err, Some(exp_found))
906 let vals = match self.values_str(&values) {
907 Some((expected, found)) => Some((expected, found)),
909 // Derived error. Cancel the emitter.
910 self.tcx.sess.diagnostic().cancel(diag);
914 (vals, exp_found, is_simple_error)
918 let span = cause.span(&self.tcx);
920 diag.span_label(span, terr.to_string());
921 if let Some((sp, msg)) = secondary_span {
922 diag.span_label(sp, msg);
925 if let Some((expected, found)) = expected_found {
926 match (terr, is_simple_error, expected == found) {
927 (&TypeError::Sorts(ref values), false, true) => {
928 diag.note_expected_found_extra(
932 &format!(" ({})", values.expected.sort_string(self.tcx)),
933 &format!(" ({})", values.found.sort_string(self.tcx)),
937 if let Some(exp_found) = exp_found {
938 let (def_id, ret_ty) = match exp_found.found.sty {
939 TyKind::FnDef(def, _) => {
940 (Some(def), Some(self.tcx.fn_sig(def).output()))
945 let exp_is_struct = match exp_found.expected.sty {
946 TyKind::Adt(def, _) => def.is_struct(),
950 if let (Some(def_id), Some(ret_ty)) = (def_id, ret_ty) {
951 if exp_is_struct && &exp_found.expected == ret_ty.skip_binder() {
952 let message = format!(
953 "did you mean `{}(/* fields */)`?",
954 self.tcx.item_path_str(def_id)
956 diag.span_label(span, message);
959 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
962 diag.note_expected_found(&"type", expected, found);
968 self.check_and_note_conflicting_crates(diag, terr, span);
969 self.tcx.note_and_explain_type_err(diag, terr, span);
971 // It reads better to have the error origin as the final
973 self.note_error_origin(diag, &cause);
976 /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
978 fn suggest_as_ref_where_appropriate(
981 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
982 diag: &mut DiagnosticBuilder<'tcx>,
984 match (&exp_found.expected.sty, &exp_found.found.sty) {
985 (TyKind::Adt(exp_def, exp_substs), TyKind::Ref(_, found_ty, _)) => {
986 if let TyKind::Adt(found_def, found_substs) = found_ty.sty {
987 let path_str = format!("{:?}", exp_def);
988 if exp_def == &found_def {
989 let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
991 let result_msg = "you can convert from `&Result<T, E>` to \
992 `Result<&T, &E>` using `.as_ref()`";
994 ("std::option::Option", opt_msg),
995 ("core::option::Option", opt_msg),
996 ("std::result::Result", result_msg),
997 ("core::result::Result", result_msg),
999 if let Some(msg) = have_as_ref.iter()
1000 .filter_map(|(path, msg)| if &path_str == path {
1006 let mut show_suggestion = true;
1007 for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1009 TyKind::Ref(_, exp_ty, _) => {
1010 match (&exp_ty.sty, &found_ty.sty) {
1011 (_, TyKind::Param(_)) |
1012 (_, TyKind::Infer(_)) |
1013 (TyKind::Param(_), _) |
1014 (TyKind::Infer(_), _) => {}
1015 _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1016 _ => show_suggestion = false,
1019 TyKind::Param(_) | TyKind::Infer(_) => {}
1020 _ => show_suggestion = false,
1023 if let (Ok(snippet), true) = (
1024 self.tcx.sess.source_map().span_to_snippet(span),
1027 diag.span_suggestion_with_applicability(
1030 format!("{}.as_ref()", snippet),
1031 Applicability::MachineApplicable,
1042 pub fn report_and_explain_type_error(
1044 trace: TypeTrace<'tcx>,
1045 terr: &TypeError<'tcx>,
1046 ) -> DiagnosticBuilder<'tcx> {
1048 "report_and_explain_type_error(trace={:?}, terr={:?})",
1052 let span = trace.cause.span(&self.tcx);
1053 let failure_code = trace.cause.as_failure_code(terr);
1054 let mut diag = match failure_code {
1055 FailureCode::Error0317(failure_str) => {
1056 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1058 FailureCode::Error0580(failure_str) => {
1059 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1061 FailureCode::Error0308(failure_str) => {
1062 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1064 FailureCode::Error0644(failure_str) => {
1065 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1068 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1074 values: &ValuePairs<'tcx>,
1075 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1077 infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1078 infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1079 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1080 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1084 fn expected_found_str_ty(
1086 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1087 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1088 let exp_found = self.resolve_type_vars_if_possible(exp_found);
1089 if exp_found.references_error() {
1093 Some(self.cmp(exp_found.expected, exp_found.found))
1096 /// Returns a string of the form "expected `{}`, found `{}`".
1097 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1099 exp_found: &ty::error::ExpectedFound<T>,
1100 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1101 let exp_found = self.resolve_type_vars_if_possible(exp_found);
1102 if exp_found.references_error() {
1107 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1108 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1112 pub fn report_generic_bound_failure(
1114 region_scope_tree: ®ion::ScopeTree,
1116 origin: Option<SubregionOrigin<'tcx>>,
1117 bound_kind: GenericKind<'tcx>,
1120 self.construct_generic_bound_failure(region_scope_tree, span, origin, bound_kind, sub)
1124 pub fn construct_generic_bound_failure(
1126 region_scope_tree: ®ion::ScopeTree,
1128 origin: Option<SubregionOrigin<'tcx>>,
1129 bound_kind: GenericKind<'tcx>,
1131 ) -> DiagnosticBuilder<'a> {
1132 // Attempt to obtain the span of the parameter so we can
1133 // suggest adding an explicit lifetime bound to it.
1134 let type_param_span = match (self.in_progress_tables, bound_kind) {
1135 (Some(ref table), GenericKind::Param(ref param)) => {
1136 let table = table.borrow();
1137 table.local_id_root.and_then(|did| {
1138 let generics = self.tcx.generics_of(did);
1139 // Account for the case where `did` corresponds to `Self`, which doesn't have
1140 // the expected type argument.
1141 if !param.is_self() {
1142 let type_param = generics.type_param(param, self.tcx);
1143 let hir = &self.tcx.hir();
1144 hir.as_local_node_id(type_param.def_id).map(|id| {
1145 // Get the `hir::Param` to verify whether it already has any bounds.
1146 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1147 // instead we suggest `T: 'a + 'b` in that case.
1148 let mut has_bounds = false;
1149 if let Node::GenericParam(ref param) = hir.get(id) {
1150 has_bounds = !param.bounds.is_empty();
1152 let sp = hir.span(id);
1153 // `sp` only covers `T`, change it so that it covers
1154 // `T:` when appropriate
1155 let is_impl_trait = bound_kind.to_string().starts_with("impl ");
1156 let sp = if has_bounds && !is_impl_trait {
1160 .next_point(self.tcx.sess.source_map().next_point(sp)))
1164 (sp, has_bounds, is_impl_trait)
1174 let labeled_user_string = match bound_kind {
1175 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1176 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1179 if let Some(SubregionOrigin::CompareImplMethodObligation {
1186 return self.report_extra_impl_obligation(
1191 &format!("`{}: {}`", bound_kind, sub),
1195 fn binding_suggestion<'tcx, S: fmt::Display>(
1196 err: &mut DiagnosticBuilder<'tcx>,
1197 type_param_span: Option<(Span, bool, bool)>,
1198 bound_kind: GenericKind<'tcx>,
1201 let consider = format!(
1202 "consider adding an explicit lifetime bound {}",
1203 if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
1204 format!(" `{}` to `{}`...", sub, bound_kind)
1206 format!("`{}: {}`...", bound_kind, sub)
1209 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1210 let suggestion = if is_impl_trait {
1211 format!("{} + {}", bound_kind, sub)
1213 let tail = if has_lifetimes { " + " } else { "" };
1214 format!("{}: {}{}", bound_kind, sub, tail)
1216 err.span_suggestion_short_with_applicability(
1220 Applicability::MaybeIncorrect, // Issue #41966
1223 err.help(&consider);
1227 let mut err = match *sub {
1229 | ty::ReFree(ty::FreeRegion {
1230 bound_region: ty::BrNamed(..),
1233 // Does the required lifetime have a nice name we can print?
1234 let mut err = struct_span_err!(
1238 "{} may not live long enough",
1241 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1246 // Does the required lifetime have a nice name we can print?
1247 let mut err = struct_span_err!(
1251 "{} may not live long enough",
1254 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1259 // If not, be less specific.
1260 let mut err = struct_span_err!(
1264 "{} may not live long enough",
1268 "consider adding an explicit lifetime bound for `{}`",
1271 self.tcx.note_and_explain_region(
1274 &format!("{} must be valid for ", labeled_user_string),
1282 if let Some(origin) = origin {
1283 self.note_region_origin(&mut err, &origin);
1288 fn report_sub_sup_conflict(
1290 region_scope_tree: ®ion::ScopeTree,
1291 var_origin: RegionVariableOrigin,
1292 sub_origin: SubregionOrigin<'tcx>,
1293 sub_region: Region<'tcx>,
1294 sup_origin: SubregionOrigin<'tcx>,
1295 sup_region: Region<'tcx>,
1297 let mut err = self.report_inference_failure(var_origin);
1299 self.tcx.note_and_explain_region(
1302 "first, the lifetime cannot outlive ",
1307 match (&sup_origin, &sub_origin) {
1308 (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1309 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1310 self.values_str(&sup_trace.values),
1311 self.values_str(&sub_trace.values),
1313 if sub_expected == sup_expected && sub_found == sup_found {
1314 self.tcx.note_and_explain_region(
1317 "...but the lifetime must also be valid for ",
1322 "...so that the {}:\nexpected {}\n found {}",
1323 sup_trace.cause.as_requirement_str(),
1324 sup_expected.content(),
1335 self.note_region_origin(&mut err, &sup_origin);
1337 self.tcx.note_and_explain_region(
1340 "but, the lifetime must be valid for ",
1345 self.note_region_origin(&mut err, &sub_origin);
1350 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1351 fn report_inference_failure(
1353 var_origin: RegionVariableOrigin,
1354 ) -> DiagnosticBuilder<'tcx> {
1355 let br_string = |br: ty::BoundRegion| {
1356 let mut s = br.to_string();
1362 let var_description = match var_origin {
1363 infer::MiscVariable(_) => String::new(),
1364 infer::PatternRegion(_) => " for pattern".to_string(),
1365 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1366 infer::Autoref(_) => " for autoref".to_string(),
1367 infer::Coercion(_) => " for automatic coercion".to_string(),
1368 infer::LateBoundRegion(_, br, infer::FnCall) => {
1369 format!(" for lifetime parameter {}in function call", br_string(br))
1371 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1372 format!(" for lifetime parameter {}in generic type", br_string(br))
1374 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1375 " for lifetime parameter {}in trait containing associated type `{}`",
1377 self.tcx.associated_item(def_id).ident
1379 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1380 infer::BoundRegionInCoherence(name) => {
1381 format!(" for lifetime parameter `{}` in coherence check", name)
1383 infer::UpvarRegion(ref upvar_id, _) => {
1384 let var_node_id = self.tcx.hir().hir_to_node_id(upvar_id.var_path.hir_id);
1385 let var_name = self.tcx.hir().name(var_node_id);
1386 format!(" for capture of `{}` by closure", var_name)
1388 infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1395 "cannot infer an appropriate lifetime{} \
1396 due to conflicting requirements",
1403 Error0317(&'static str),
1404 Error0580(&'static str),
1405 Error0308(&'static str),
1406 Error0644(&'static str),
1409 impl<'tcx> ObligationCause<'tcx> {
1410 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1411 use self::FailureCode::*;
1412 use traits::ObligationCauseCode::*;
1414 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1415 MatchExpressionArm { source, .. } => Error0308(match source {
1416 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have incompatible types",
1417 hir::MatchSource::TryDesugar => {
1418 "try expression alternatives have incompatible types"
1420 _ => "match arms have incompatible types",
1422 IfExpression => Error0308("if and else have incompatible types"),
1423 IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1424 MainFunctionType => Error0580("main function has wrong type"),
1425 StartFunctionType => Error0308("start function has wrong type"),
1426 IntrinsicType => Error0308("intrinsic has wrong type"),
1427 MethodReceiver => Error0308("mismatched method receiver"),
1429 // In the case where we have no more specific thing to
1430 // say, also take a look at the error code, maybe we can
1433 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1434 Error0644("closure/generator type that references itself")
1436 _ => Error0308("mismatched types"),
1441 fn as_requirement_str(&self) -> &'static str {
1442 use traits::ObligationCauseCode::*;
1444 CompareImplMethodObligation { .. } => "method type is compatible with trait",
1445 ExprAssignable => "expression is assignable",
1446 MatchExpressionArm { source, .. } => match source {
1447 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1448 _ => "match arms have compatible types",
1450 IfExpression => "if and else have compatible types",
1451 IfExpressionWithNoElse => "if missing an else returns ()",
1452 MainFunctionType => "`main` function has the correct type",
1453 StartFunctionType => "`start` function has the correct type",
1454 IntrinsicType => "intrinsic has the correct type",
1455 MethodReceiver => "method receiver has the correct type",
1456 _ => "types are compatible",