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 ty::RePlaceholder(_) => (format!("any other region"), None),
137 // FIXME(#13998) RePlaceholder should probably print like
138 // ReFree rather than dumping Debug output on the user.
140 // We shouldn't really be having unification failures with ReVar
141 // and ReLateBound though.
142 ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
143 (format!("lifetime {:?}", region), None)
146 // We shouldn't encounter an error message with ReClosureBound.
147 ty::ReClosureBound(..) => {
148 bug!("encountered unexpected ReClosureBound: {:?}", region,);
152 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
155 pub fn note_and_explain_free_region(
157 err: &mut DiagnosticBuilder<'_>,
159 region: ty::Region<'tcx>,
162 let (description, span) = self.msg_span_from_free_region(region);
164 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
167 fn msg_span_from_free_region(self, region: ty::Region<'tcx>) -> (String, Option<Span>) {
169 ty::ReEarlyBound(_) | ty::ReFree(_) => {
170 self.msg_span_from_early_bound_and_free_regions(region)
172 ty::ReStatic => ("the static lifetime".to_owned(), None),
173 ty::ReEmpty => ("an empty lifetime".to_owned(), None),
174 _ => bug!("{:?}", region),
178 fn msg_span_from_early_bound_and_free_regions(
180 region: ty::Region<'tcx>,
181 ) -> (String, Option<Span>) {
182 let cm = self.sess.source_map();
184 let scope = region.free_region_binding_scope(self);
185 let node = self.hir().as_local_node_id(scope).unwrap_or(DUMMY_NODE_ID);
186 let tag = match self.hir().find(node) {
187 Some(Node::Block(_)) | Some(Node::Expr(_)) => "body",
188 Some(Node::Item(it)) => Self::item_scope_tag(&it),
189 Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
190 Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
193 let (prefix, span) = match *region {
194 ty::ReEarlyBound(ref br) => {
195 let mut sp = cm.def_span(self.hir().span(node));
196 if let Some(param) = self.hir()
198 .and_then(|generics| generics.get_named(&br.name))
202 (format!("the lifetime {} as defined on", br.name), sp)
204 ty::ReFree(ty::FreeRegion {
205 bound_region: ty::BoundRegion::BrNamed(_, ref name),
208 let mut sp = cm.def_span(self.hir().span(node));
209 if let Some(param) = self.hir()
211 .and_then(|generics| generics.get_named(&name))
215 (format!("the lifetime {} as defined on", name), sp)
217 ty::ReFree(ref fr) => match fr.bound_region {
219 format!("the anonymous lifetime #{} defined on", idx + 1),
220 self.hir().span(node),
223 "an anonymous lifetime defined on".to_owned(),
224 self.hir().span(node),
227 format!("the lifetime {} as defined on", fr.bound_region),
228 cm.def_span(self.hir().span(node)),
233 let (msg, opt_span) = self.explain_span(tag, span);
234 (format!("{} {}", prefix, msg), opt_span)
238 err: &mut DiagnosticBuilder<'_>,
244 let message = format!("{}{}{}", prefix, description, suffix);
246 if let Some(span) = span {
247 err.span_note(span, &message);
253 fn item_scope_tag(item: &hir::Item) -> &'static str {
255 hir::ItemKind::Impl(..) => "impl",
256 hir::ItemKind::Struct(..) => "struct",
257 hir::ItemKind::Union(..) => "union",
258 hir::ItemKind::Enum(..) => "enum",
259 hir::ItemKind::Trait(..) => "trait",
260 hir::ItemKind::Fn(..) => "function body",
265 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
267 hir::TraitItemKind::Method(..) => "method body",
268 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
272 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
274 hir::ImplItemKind::Method(..) => "method body",
275 hir::ImplItemKind::Const(..)
276 | hir::ImplItemKind::Existential(..)
277 | hir::ImplItemKind::Type(..) => "associated item",
281 fn explain_span(self, heading: &str, span: Span) -> (String, Option<Span>) {
282 let lo = self.sess.source_map().lookup_char_pos_adj(span.lo());
284 format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
290 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
291 pub fn report_region_errors(
293 region_scope_tree: ®ion::ScopeTree,
294 errors: &Vec<RegionResolutionError<'tcx>>,
295 suppress: SuppressRegionErrors,
298 "report_region_errors(): {} errors to start, suppress = {:?}",
303 if suppress.suppressed() {
307 // try to pre-process the errors, which will group some of them
308 // together into a `ProcessedErrors` group:
309 let errors = self.process_errors(errors);
312 "report_region_errors: {} errors after preprocessing",
316 for error in errors {
317 debug!("report_region_errors: error = {:?}", error);
319 if !self.try_report_nice_region_error(&error) {
320 match error.clone() {
321 // These errors could indicate all manner of different
322 // problems with many different solutions. Rather
323 // than generate a "one size fits all" error, what we
324 // attempt to do is go through a number of specific
325 // scenarios and try to find the best way to present
326 // the error. If all of these fails, we fall back to a rather
327 // general bit of code that displays the error information
328 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
329 if sub.is_placeholder() || sup.is_placeholder() {
330 self.report_placeholder_failure(region_scope_tree, origin, sub, sup)
333 self.report_concrete_failure(region_scope_tree, origin, sub, sup)
338 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
339 self.report_generic_bound_failure(
348 RegionResolutionError::SubSupConflict(
356 if sub_r.is_placeholder() {
357 self.report_placeholder_failure(
364 } else if sup_r.is_placeholder() {
365 self.report_placeholder_failure(
373 self.report_sub_sup_conflict(
388 // This method goes through all the errors and try to group certain types
389 // of error together, for the purpose of suggesting explicit lifetime
390 // parameters to the user. This is done so that we can have a more
391 // complete view of what lifetimes should be the same.
392 // If the return value is an empty vector, it means that processing
393 // failed (so the return value of this method should not be used).
395 // The method also attempts to weed out messages that seem like
396 // duplicates that will be unhelpful to the end-user. But
397 // obviously it never weeds out ALL errors.
400 errors: &Vec<RegionResolutionError<'tcx>>,
401 ) -> Vec<RegionResolutionError<'tcx>> {
402 debug!("process_errors()");
404 // We want to avoid reporting generic-bound failures if we can
405 // avoid it: these have a very high rate of being unhelpful in
406 // practice. This is because they are basically secondary
407 // checks that test the state of the region graph after the
408 // rest of inference is done, and the other kinds of errors
409 // indicate that the region constraint graph is internally
410 // inconsistent, so these test results are likely to be
413 // Therefore, we filter them out of the list unless they are
414 // the only thing in the list.
416 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
417 RegionResolutionError::GenericBoundFailure(..) => true,
418 RegionResolutionError::ConcreteFailure(..)
419 | RegionResolutionError::SubSupConflict(..) => false,
422 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
427 .filter(|&e| !is_bound_failure(e))
432 // sort the errors by span, for better error message stability.
433 errors.sort_by_key(|u| match *u {
434 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
435 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
436 RegionResolutionError::SubSupConflict(_, ref rvo, _, _, _, _) => rvo.span(),
441 /// Adds a note if the types come from similarly named crates
442 fn check_and_note_conflicting_crates(
444 err: &mut DiagnosticBuilder<'_>,
445 terr: &TypeError<'tcx>,
448 let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
449 // Only external crates, if either is from a local
450 // module we could have false positives
451 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
452 let exp_path = self.tcx.item_path_str(did1);
453 let found_path = self.tcx.item_path_str(did2);
454 let exp_abs_path = self.tcx.absolute_item_path_str(did1);
455 let found_abs_path = self.tcx.absolute_item_path_str(did2);
456 // We compare strings because DefPath can be different
457 // for imported and non-imported crates
458 if exp_path == found_path || exp_abs_path == found_abs_path {
459 let crate_name = self.tcx.crate_name(did1.krate);
463 "Perhaps two different versions \
464 of crate `{}` are being used?",
472 TypeError::Sorts(ref exp_found) => {
473 // if they are both "path types", there's a chance of ambiguity
474 // due to different versions of the same crate
475 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _))
476 = (&exp_found.expected.sty, &exp_found.found.sty)
478 report_path_match(err, exp_adt.did, found_adt.did);
481 TypeError::Traits(ref exp_found) => {
482 report_path_match(err, exp_found.expected, exp_found.found);
484 _ => (), // FIXME(#22750) handle traits and stuff
488 fn note_error_origin(&self, err: &mut DiagnosticBuilder<'tcx>, cause: &ObligationCause<'tcx>) {
490 ObligationCauseCode::MatchExpressionArmPattern { span, ty } => {
491 err.span_label(span, format!("this match expression has type `{}`", ty));
493 ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
494 hir::MatchSource::IfLetDesugar { .. } => {
495 let msg = "`if let` arm with an incompatible type";
496 if self.tcx.sess.source_map().is_multiline(arm_span) {
497 err.span_note(arm_span, msg);
499 err.span_label(arm_span, msg);
502 hir::MatchSource::TryDesugar => {}
504 let msg = "match arm with an incompatible type";
505 if self.tcx.sess.source_map().is_multiline(arm_span) {
506 err.span_note(arm_span, msg);
508 err.span_label(arm_span, msg);
516 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
517 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
518 /// populate `other_value` with `other_ty`.
522 /// ^^^^--------^ this is highlighted
524 /// | this type argument is exactly the same as the other type, not highlighted
525 /// this is highlighted
527 /// -------- this type is the same as a type argument in the other type, not highlighted
531 value: &mut DiagnosticStyledString,
532 other_value: &mut DiagnosticStyledString,
534 sub: &ty::subst::Substs<'tcx>,
538 // `value` and `other_value` hold two incomplete type representation for display.
539 // `name` is the path of both types being compared. `sub`
540 value.push_highlighted(name);
543 value.push_highlighted("<");
546 // Output the lifetimes for the first type
547 let lifetimes = sub.regions()
549 let s = lifetime.to_string();
558 if !lifetimes.is_empty() {
559 if sub.regions().count() < len {
560 value.push_normal(lifetimes + &", ");
562 value.push_normal(lifetimes);
566 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
567 // `pos` and `other_ty`.
568 for (i, type_arg) in sub.types().enumerate() {
570 let values = self.cmp(type_arg, other_ty);
571 value.0.extend((values.0).0);
572 other_value.0.extend((values.1).0);
574 value.push_highlighted(type_arg.to_string());
577 if len > 0 && i != len - 1 {
578 value.push_normal(", ");
580 //self.push_comma(&mut value, &mut other_value, len, i);
583 value.push_highlighted(">");
587 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
588 /// as that is the difference to the other type.
590 /// For the following code:
593 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
596 /// The type error output will behave in the following way:
600 /// ^^^^--------^ this is highlighted
602 /// | this type argument is exactly the same as the other type, not highlighted
603 /// this is highlighted
605 /// -------- this type is the same as a type argument in the other type, not highlighted
609 mut t1_out: &mut DiagnosticStyledString,
610 mut t2_out: &mut DiagnosticStyledString,
612 sub: &ty::subst::Substs<'tcx>,
616 for (i, ta) in sub.types().enumerate() {
618 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
621 if let &ty::Adt(def, _) = &ta.sty {
622 let path_ = self.tcx.item_path_str(def.did.clone());
623 if path_ == other_path {
624 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
632 /// Add a `,` to the type representation only if it is appropriate.
635 value: &mut DiagnosticStyledString,
636 other_value: &mut DiagnosticStyledString,
640 if len > 0 && pos != len - 1 {
641 value.push_normal(", ");
642 other_value.push_normal(", ");
646 /// For generic types with parameters with defaults, remove the parameters corresponding to
647 /// the defaults. This repeats a lot of the logic found in `PrintContext::parameterized`.
648 fn strip_generic_default_params(
651 substs: &ty::subst::Substs<'tcx>,
652 ) -> &'tcx ty::subst::Substs<'tcx> {
653 let generics = self.tcx.generics_of(def_id);
654 let mut num_supplied_defaults = 0;
655 let mut type_params = generics
659 .filter_map(|param| match param.kind {
660 ty::GenericParamDefKind::Lifetime => None,
661 ty::GenericParamDefKind::Type { has_default, .. } => {
662 Some((param.def_id, has_default))
667 let has_default = type_params.peek().map(|(_, has_default)| has_default);
668 *has_default.unwrap_or(&false)
671 let types = substs.types().rev();
672 for ((def_id, has_default), actual) in type_params.zip(types) {
676 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
679 num_supplied_defaults += 1;
682 let len = generics.params.len();
683 let mut generics = generics.clone();
684 generics.params.truncate(len - num_supplied_defaults);
685 substs.truncate_to(self.tcx, &generics)
688 /// Compare two given types, eliding parts that are the same between them and highlighting
689 /// relevant differences, and return two representation of those types for highlighted printing.
690 fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
691 fn equals<'tcx>(a: &Ty<'tcx>, b: &Ty<'tcx>) -> bool {
692 match (&a.sty, &b.sty) {
693 (a, b) if *a == *b => true,
694 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
695 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_))
696 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Infer(ty::InferTy::IntVar(_)))
697 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
698 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Float(_))
699 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Infer(ty::InferTy::FloatVar(_))) => {
706 fn push_ty_ref<'tcx>(
707 r: &ty::Region<'tcx>,
709 mutbl: hir::Mutability,
710 s: &mut DiagnosticStyledString,
712 let r = &r.to_string();
713 s.push_highlighted(format!(
716 if r == "" { "" } else { " " },
717 if mutbl == hir::MutMutable { "mut " } else { "" }
719 s.push_normal(ty.to_string());
722 match (&t1.sty, &t2.sty) {
723 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
724 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
725 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
726 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
727 let path1 = self.tcx.item_path_str(def1.did.clone());
728 let path2 = self.tcx.item_path_str(def2.did.clone());
729 if def1.did == def2.did {
730 // Easy case. Replace same types with `_` to shorten the output and highlight
731 // the differing ones.
732 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
735 // --- ^ type argument elided
737 // highlighted in output
738 values.0.push_normal(path1);
739 values.1.push_normal(path2);
741 // Avoid printing out default generic parameters that are common to both
743 let len1 = sub_no_defaults_1.len();
744 let len2 = sub_no_defaults_2.len();
745 let common_len = cmp::min(len1, len2);
746 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
747 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
748 let common_default_params = remainder1
751 .zip(remainder2.iter().rev())
752 .filter(|(a, b)| a == b)
754 let len = sub1.len() - common_default_params;
756 // Only draw `<...>` if there're lifetime/type arguments.
758 values.0.push_normal("<");
759 values.1.push_normal("<");
762 fn lifetime_display(lifetime: Region<'_>) -> String {
763 let s = lifetime.to_string();
770 // At one point we'd like to elide all lifetimes here, they are irrelevant for
771 // all diagnostics that use this output
775 // ^^ ^^ --- type arguments are not elided
777 // | elided as they were the same
778 // not elided, they were different, but irrelevant
779 let lifetimes = sub1.regions().zip(sub2.regions());
780 for (i, lifetimes) in lifetimes.enumerate() {
781 let l1 = lifetime_display(lifetimes.0);
782 let l2 = lifetime_display(lifetimes.1);
784 values.0.push_normal("'_");
785 values.1.push_normal("'_");
787 values.0.push_highlighted(l1);
788 values.1.push_highlighted(l2);
790 self.push_comma(&mut values.0, &mut values.1, len, i);
793 // We're comparing two types with the same path, so we compare the type
794 // arguments for both. If they are the same, do not highlight and elide from the
798 // ^ elided type as this type argument was the same in both sides
799 let type_arguments = sub1.types().zip(sub2.types());
800 let regions_len = sub1.regions().count();
801 for (i, (ta1, ta2)) in type_arguments.take(len).enumerate() {
802 let i = i + regions_len;
804 values.0.push_normal("_");
805 values.1.push_normal("_");
807 let (x1, x2) = self.cmp(ta1, ta2);
808 (values.0).0.extend(x1.0);
809 (values.1).0.extend(x2.0);
811 self.push_comma(&mut values.0, &mut values.1, len, i);
814 // Close the type argument bracket.
815 // Only draw `<...>` if there're lifetime/type arguments.
817 values.0.push_normal(">");
818 values.1.push_normal(">");
823 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
825 // ------- this type argument is exactly the same as the other type
827 if self.cmp_type_arg(
839 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
842 // ------- this type argument is exactly the same as the other type
843 if self.cmp_type_arg(
855 // We couldn't find anything in common, highlight everything.
856 // let x: Bar<Qux> = y::<Foo<Zar>>();
858 DiagnosticStyledString::highlighted(t1.to_string()),
859 DiagnosticStyledString::highlighted(t2.to_string()),
864 // When finding T != &T, highlight only the borrow
865 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
866 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
867 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
868 values.1.push_normal(t2.to_string());
871 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
872 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
873 values.0.push_normal(t1.to_string());
874 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
878 // When encountering &T != &mut T, highlight only the borrow
879 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
880 if equals(&ref_ty1, &ref_ty2) =>
882 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
883 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
884 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
890 // The two types are the same, elide and don't highlight.
892 DiagnosticStyledString::normal("_"),
893 DiagnosticStyledString::normal("_"),
896 // We couldn't find anything in common, highlight everything.
898 DiagnosticStyledString::highlighted(t1.to_string()),
899 DiagnosticStyledString::highlighted(t2.to_string()),
906 pub fn note_type_err(
908 diag: &mut DiagnosticBuilder<'tcx>,
909 cause: &ObligationCause<'tcx>,
910 secondary_span: Option<(Span, String)>,
911 mut values: Option<ValuePairs<'tcx>>,
912 terr: &TypeError<'tcx>,
914 // For some types of errors, expected-found does not make
915 // sense, so just ignore the values we were given.
917 TypeError::CyclicTy(_) => {
923 let (expected_found, exp_found, is_simple_error) = match values {
924 None => (None, None, false),
926 let (is_simple_error, exp_found) = match values {
927 ValuePairs::Types(exp_found) => {
929 exp_found.expected.is_primitive() && exp_found.found.is_primitive();
931 (is_simple_err, Some(exp_found))
935 let vals = match self.values_str(&values) {
936 Some((expected, found)) => Some((expected, found)),
938 // Derived error. Cancel the emitter.
939 self.tcx.sess.diagnostic().cancel(diag);
943 (vals, exp_found, is_simple_error)
947 let span = cause.span(&self.tcx);
949 diag.span_label(span, terr.to_string());
950 if let Some((sp, msg)) = secondary_span {
951 diag.span_label(sp, msg);
954 if let Some((expected, found)) = expected_found {
955 match (terr, is_simple_error, expected == found) {
956 (&TypeError::Sorts(ref values), false, true) => {
957 diag.note_expected_found_extra(
961 &format!(" ({})", values.expected.sort_string(self.tcx)),
962 &format!(" ({})", values.found.sort_string(self.tcx)),
966 if let Some(exp_found) = exp_found {
967 let (def_id, ret_ty) = match exp_found.found.sty {
968 TyKind::FnDef(def, _) => {
969 (Some(def), Some(self.tcx.fn_sig(def).output()))
974 let exp_is_struct = match exp_found.expected.sty {
975 TyKind::Adt(def, _) => def.is_struct(),
979 if let (Some(def_id), Some(ret_ty)) = (def_id, ret_ty) {
980 if exp_is_struct && &exp_found.expected == ret_ty.skip_binder() {
981 let message = format!(
982 "did you mean `{}(/* fields */)`?",
983 self.tcx.item_path_str(def_id)
985 diag.span_label(span, message);
988 self.suggest_as_ref_where_appropriate(span, &exp_found, diag);
991 diag.note_expected_found(&"type", expected, found);
997 self.check_and_note_conflicting_crates(diag, terr, span);
998 self.tcx.note_and_explain_type_err(diag, terr, span);
1000 // It reads better to have the error origin as the final
1002 self.note_error_origin(diag, &cause);
1005 /// When encountering a case where `.as_ref()` on a `Result` or `Option` would be appropriate,
1007 fn suggest_as_ref_where_appropriate(
1010 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1011 diag: &mut DiagnosticBuilder<'tcx>,
1013 match (&exp_found.expected.sty, &exp_found.found.sty) {
1014 (TyKind::Adt(exp_def, exp_substs), TyKind::Ref(_, found_ty, _)) => {
1015 if let TyKind::Adt(found_def, found_substs) = found_ty.sty {
1016 let path_str = format!("{:?}", exp_def);
1017 if exp_def == &found_def {
1018 let opt_msg = "you can convert from `&Option<T>` to `Option<&T>` using \
1020 let result_msg = "you can convert from `&Result<T, E>` to \
1021 `Result<&T, &E>` using `.as_ref()`";
1022 let have_as_ref = &[
1023 ("std::option::Option", opt_msg),
1024 ("core::option::Option", opt_msg),
1025 ("std::result::Result", result_msg),
1026 ("core::result::Result", result_msg),
1028 if let Some(msg) = have_as_ref.iter()
1029 .filter_map(|(path, msg)| if &path_str == path {
1035 let mut show_suggestion = true;
1036 for (exp_ty, found_ty) in exp_substs.types().zip(found_substs.types()) {
1038 TyKind::Ref(_, exp_ty, _) => {
1039 match (&exp_ty.sty, &found_ty.sty) {
1040 (_, TyKind::Param(_)) |
1041 (_, TyKind::Infer(_)) |
1042 (TyKind::Param(_), _) |
1043 (TyKind::Infer(_), _) => {}
1044 _ if ty::TyS::same_type(exp_ty, found_ty) => {}
1045 _ => show_suggestion = false,
1048 TyKind::Param(_) | TyKind::Infer(_) => {}
1049 _ => show_suggestion = false,
1052 if let (Ok(snippet), true) = (
1053 self.tcx.sess.source_map().span_to_snippet(span),
1056 diag.span_suggestion_with_applicability(
1059 format!("{}.as_ref()", snippet),
1060 Applicability::MachineApplicable,
1071 pub fn report_and_explain_type_error(
1073 trace: TypeTrace<'tcx>,
1074 terr: &TypeError<'tcx>,
1075 ) -> DiagnosticBuilder<'tcx> {
1077 "report_and_explain_type_error(trace={:?}, terr={:?})",
1081 let span = trace.cause.span(&self.tcx);
1082 let failure_code = trace.cause.as_failure_code(terr);
1083 let mut diag = match failure_code {
1084 FailureCode::Error0317(failure_str) => {
1085 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1087 FailureCode::Error0580(failure_str) => {
1088 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1090 FailureCode::Error0308(failure_str) => {
1091 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1093 FailureCode::Error0644(failure_str) => {
1094 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1097 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1103 values: &ValuePairs<'tcx>,
1104 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1106 infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1107 infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1108 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1109 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1113 fn expected_found_str_ty(
1115 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1116 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1117 let exp_found = self.resolve_type_vars_if_possible(exp_found);
1118 if exp_found.references_error() {
1122 Some(self.cmp(exp_found.expected, exp_found.found))
1125 /// Returns a string of the form "expected `{}`, found `{}`".
1126 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1128 exp_found: &ty::error::ExpectedFound<T>,
1129 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1130 let exp_found = self.resolve_type_vars_if_possible(exp_found);
1131 if exp_found.references_error() {
1136 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1137 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1141 pub fn report_generic_bound_failure(
1143 region_scope_tree: ®ion::ScopeTree,
1145 origin: Option<SubregionOrigin<'tcx>>,
1146 bound_kind: GenericKind<'tcx>,
1149 self.construct_generic_bound_failure(region_scope_tree, span, origin, bound_kind, sub)
1153 pub fn construct_generic_bound_failure(
1155 region_scope_tree: ®ion::ScopeTree,
1157 origin: Option<SubregionOrigin<'tcx>>,
1158 bound_kind: GenericKind<'tcx>,
1160 ) -> DiagnosticBuilder<'a> {
1161 // Attempt to obtain the span of the parameter so we can
1162 // suggest adding an explicit lifetime bound to it.
1163 let type_param_span = match (self.in_progress_tables, bound_kind) {
1164 (Some(ref table), GenericKind::Param(ref param)) => {
1165 let table = table.borrow();
1166 table.local_id_root.and_then(|did| {
1167 let generics = self.tcx.generics_of(did);
1168 // Account for the case where `did` corresponds to `Self`, which doesn't have
1169 // the expected type argument.
1170 if !param.is_self() {
1171 let type_param = generics.type_param(param, self.tcx);
1172 let hir = &self.tcx.hir();
1173 hir.as_local_node_id(type_param.def_id).map(|id| {
1174 // Get the `hir::Param` to verify whether it already has any bounds.
1175 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1176 // instead we suggest `T: 'a + 'b` in that case.
1177 let mut has_bounds = false;
1178 if let Node::GenericParam(ref param) = hir.get(id) {
1179 has_bounds = !param.bounds.is_empty();
1181 let sp = hir.span(id);
1182 // `sp` only covers `T`, change it so that it covers
1183 // `T:` when appropriate
1184 let is_impl_trait = bound_kind.to_string().starts_with("impl ");
1185 let sp = if has_bounds && !is_impl_trait {
1189 .next_point(self.tcx.sess.source_map().next_point(sp)))
1193 (sp, has_bounds, is_impl_trait)
1203 let labeled_user_string = match bound_kind {
1204 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1205 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1208 if let Some(SubregionOrigin::CompareImplMethodObligation {
1215 return self.report_extra_impl_obligation(
1220 &format!("`{}: {}`", bound_kind, sub),
1224 fn binding_suggestion<'tcx, S: fmt::Display>(
1225 err: &mut DiagnosticBuilder<'tcx>,
1226 type_param_span: Option<(Span, bool, bool)>,
1227 bound_kind: GenericKind<'tcx>,
1230 let consider = format!(
1231 "consider adding an explicit lifetime bound {}",
1232 if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
1233 format!(" `{}` to `{}`...", sub, bound_kind)
1235 format!("`{}: {}`...", bound_kind, sub)
1238 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1239 let suggestion = if is_impl_trait {
1240 format!("{} + {}", bound_kind, sub)
1242 let tail = if has_lifetimes { " + " } else { "" };
1243 format!("{}: {}{}", bound_kind, sub, tail)
1245 err.span_suggestion_short_with_applicability(
1249 Applicability::MaybeIncorrect, // Issue #41966
1252 err.help(&consider);
1256 let mut err = match *sub {
1258 | ty::ReFree(ty::FreeRegion {
1259 bound_region: ty::BrNamed(..),
1262 // Does the required lifetime have a nice name we can print?
1263 let mut err = struct_span_err!(
1267 "{} may not live long enough",
1270 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1275 // Does the required lifetime have a nice name we can print?
1276 let mut err = struct_span_err!(
1280 "{} may not live long enough",
1283 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1288 // If not, be less specific.
1289 let mut err = struct_span_err!(
1293 "{} may not live long enough",
1297 "consider adding an explicit lifetime bound for `{}`",
1300 self.tcx.note_and_explain_region(
1303 &format!("{} must be valid for ", labeled_user_string),
1311 if let Some(origin) = origin {
1312 self.note_region_origin(&mut err, &origin);
1317 fn report_sub_sup_conflict(
1319 region_scope_tree: ®ion::ScopeTree,
1320 var_origin: RegionVariableOrigin,
1321 sub_origin: SubregionOrigin<'tcx>,
1322 sub_region: Region<'tcx>,
1323 sup_origin: SubregionOrigin<'tcx>,
1324 sup_region: Region<'tcx>,
1326 let mut err = self.report_inference_failure(var_origin);
1328 self.tcx.note_and_explain_region(
1331 "first, the lifetime cannot outlive ",
1336 match (&sup_origin, &sub_origin) {
1337 (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1338 debug!("report_sub_sup_conflict: var_origin={:?}", var_origin);
1339 debug!("report_sub_sup_conflict: sub_region={:?}", sub_region);
1340 debug!("report_sub_sup_conflict: sub_origin={:?}", sub_origin);
1341 debug!("report_sub_sup_conflict: sup_region={:?}", sup_region);
1342 debug!("report_sub_sup_conflict: sup_origin={:?}", sup_origin);
1343 debug!("report_sub_sup_conflict: sup_trace={:?}", sup_trace);
1344 debug!("report_sub_sup_conflict: sub_trace={:?}", sub_trace);
1345 debug!("report_sub_sup_conflict: sup_trace.values={:?}", sup_trace.values);
1346 debug!("report_sub_sup_conflict: sub_trace.values={:?}", sub_trace.values);
1348 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1349 self.values_str(&sup_trace.values),
1350 self.values_str(&sub_trace.values),
1352 if sub_expected == sup_expected && sub_found == sup_found {
1353 self.tcx.note_and_explain_region(
1356 "...but the lifetime must also be valid for ",
1361 "...so that the {}:\nexpected {}\n found {}",
1362 sup_trace.cause.as_requirement_str(),
1363 sup_expected.content(),
1374 self.note_region_origin(&mut err, &sup_origin);
1376 self.tcx.note_and_explain_region(
1379 "but, the lifetime must be valid for ",
1384 self.note_region_origin(&mut err, &sub_origin);
1389 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1390 fn report_inference_failure(
1392 var_origin: RegionVariableOrigin,
1393 ) -> DiagnosticBuilder<'tcx> {
1394 let br_string = |br: ty::BoundRegion| {
1395 let mut s = br.to_string();
1401 let var_description = match var_origin {
1402 infer::MiscVariable(_) => String::new(),
1403 infer::PatternRegion(_) => " for pattern".to_string(),
1404 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1405 infer::Autoref(_) => " for autoref".to_string(),
1406 infer::Coercion(_) => " for automatic coercion".to_string(),
1407 infer::LateBoundRegion(_, br, infer::FnCall) => {
1408 format!(" for lifetime parameter {}in function call", br_string(br))
1410 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1411 format!(" for lifetime parameter {}in generic type", br_string(br))
1413 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1414 " for lifetime parameter {}in trait containing associated type `{}`",
1416 self.tcx.associated_item(def_id).ident
1418 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1419 infer::BoundRegionInCoherence(name) => {
1420 format!(" for lifetime parameter `{}` in coherence check", name)
1422 infer::UpvarRegion(ref upvar_id, _) => {
1423 let var_node_id = self.tcx.hir().hir_to_node_id(upvar_id.var_path.hir_id);
1424 let var_name = self.tcx.hir().name(var_node_id);
1425 format!(" for capture of `{}` by closure", var_name)
1427 infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1434 "cannot infer an appropriate lifetime{} \
1435 due to conflicting requirements",
1442 Error0317(&'static str),
1443 Error0580(&'static str),
1444 Error0308(&'static str),
1445 Error0644(&'static str),
1448 impl<'tcx> ObligationCause<'tcx> {
1449 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1450 use self::FailureCode::*;
1451 use traits::ObligationCauseCode::*;
1453 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1454 MatchExpressionArm { source, .. } => Error0308(match source {
1455 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have incompatible types",
1456 hir::MatchSource::TryDesugar => {
1457 "try expression alternatives have incompatible types"
1459 _ => "match arms have incompatible types",
1461 IfExpression => Error0308("if and else have incompatible types"),
1462 IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1463 MainFunctionType => Error0580("main function has wrong type"),
1464 StartFunctionType => Error0308("start function has wrong type"),
1465 IntrinsicType => Error0308("intrinsic has wrong type"),
1466 MethodReceiver => Error0308("mismatched method receiver"),
1468 // In the case where we have no more specific thing to
1469 // say, also take a look at the error code, maybe we can
1472 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1473 Error0644("closure/generator type that references itself")
1475 _ => Error0308("mismatched types"),
1480 fn as_requirement_str(&self) -> &'static str {
1481 use traits::ObligationCauseCode::*;
1483 CompareImplMethodObligation { .. } => "method type is compatible with trait",
1484 ExprAssignable => "expression is assignable",
1485 MatchExpressionArm { source, .. } => match source {
1486 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1487 _ => "match arms have compatible types",
1489 IfExpression => "if and else have compatible types",
1490 IfExpressionWithNoElse => "if missing an else returns ()",
1491 MainFunctionType => "`main` function has the correct type",
1492 StartFunctionType => "`start` function has the correct type",
1493 IntrinsicType => "intrinsic has the correct type",
1494 MethodReceiver => "method receiver has the correct type",
1495 _ => "types are compatible",