1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Error Reporting Code for the inference engine
13 //! Because of the way inference, and in particular region inference,
14 //! works, it often happens that errors are not detected until far after
15 //! the relevant line of code has been type-checked. Therefore, there is
16 //! an elaborate system to track why a particular constraint in the
17 //! inference graph arose so that we can explain to the user what gave
18 //! rise to a particular error.
20 //! The basis of the system are the "origin" types. An "origin" is the
21 //! reason that a constraint or inference variable arose. There are
22 //! different "origin" enums for different kinds of constraints/variables
23 //! (e.g., `TypeOrigin`, `RegionVariableOrigin`). An origin always has
24 //! a span, but also more information so that we can generate a meaningful
27 //! Having a catalog of all the different reasons an error can arise is
28 //! also useful for other reasons, like cross-referencing FAQs etc, though
29 //! we are not really taking advantage of this yet.
31 //! # Region Inference
33 //! Region inference is particularly tricky because it always succeeds "in
34 //! the moment" and simply registers a constraint. Then, at the end, we
35 //! can compute the full graph and report errors, so we need to be able to
36 //! store and later report what gave rise to the conflicting constraints.
40 //! Determining whether `T1 <: T2` often involves a number of subtypes and
41 //! subconstraints along the way. A "TypeTrace" is an extended version
42 //! of an origin that traces the types and other values that were being
43 //! compared. It is not necessarily comprehensive (in fact, at the time of
44 //! this writing it only tracks the root values being compared) but I'd
45 //! like to extend it to include significant "waypoints". For example, if
46 //! you are comparing `(T1, T2) <: (T3, T4)`, and the problem is that `T2
47 //! <: T4` fails, I'd like the trace to include enough information to say
48 //! "in the 2nd element of the tuple". Similarly, failures when comparing
49 //! arguments or return types in fn types should be able to cite the
50 //! specific position, etc.
54 //! Of course, there is still a LOT of code in typeck that has yet to be
55 //! ported to this system, and which relies on string concatenation at the
56 //! time of error detection.
59 use super::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePairs};
60 use super::region_constraints::GenericKind;
61 use super::lexical_region_resolve::RegionResolutionError;
65 use hir::map as hir_map;
66 use hir::def_id::DefId;
68 use traits::{ObligationCause, ObligationCauseCode};
69 use ty::{self, Region, Ty, TyCtxt, TypeFoldable, TypeVariants};
70 use ty::error::TypeError;
71 use syntax::ast::DUMMY_NODE_ID;
72 use syntax_pos::{Pos, Span};
73 use errors::{DiagnosticBuilder, DiagnosticStyledString};
75 use rustc_data_structures::indexed_vec::Idx;
81 pub mod nice_region_error;
83 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
84 pub fn note_and_explain_region(
86 region_scope_tree: ®ion::ScopeTree,
87 err: &mut DiagnosticBuilder,
89 region: ty::Region<'tcx>,
92 let (description, span) = match *region {
93 ty::ReScope(scope) => {
95 let unknown_scope = || {
97 "{}unknown scope: {:?}{}. Please report a bug.",
101 let span = scope.span(self, region_scope_tree);
102 let tag = match self.hir.find(scope.node_id(self, region_scope_tree)) {
103 Some(hir_map::NodeBlock(_)) => "block",
104 Some(hir_map::NodeExpr(expr)) => match expr.node {
105 hir::ExprCall(..) => "call",
106 hir::ExprMethodCall(..) => "method call",
107 hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
108 hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) => "while let",
109 hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) => "for",
110 hir::ExprMatch(..) => "match",
113 Some(hir_map::NodeStmt(_)) => "statement",
114 Some(hir_map::NodeItem(it)) => Self::item_scope_tag(&it),
115 Some(hir_map::NodeTraitItem(it)) => Self::trait_item_scope_tag(&it),
116 Some(hir_map::NodeImplItem(it)) => Self::impl_item_scope_tag(&it),
118 err.span_note(span, &unknown_scope());
122 let scope_decorated_tag = match scope.data() {
123 region::ScopeData::Node(_) => tag,
124 region::ScopeData::CallSite(_) => "scope of call-site for function",
125 region::ScopeData::Arguments(_) => "scope of function body",
126 region::ScopeData::Destruction(_) => {
127 new_string = format!("destruction scope surrounding {}", tag);
130 region::ScopeData::Remainder(r) => {
131 new_string = format!(
132 "block suffix following statement {}",
133 r.first_statement_index.index()
138 self.explain_span(scope_decorated_tag, span)
141 ty::ReEarlyBound(_) | ty::ReFree(_) => self.msg_span_from_free_region(region),
143 ty::ReStatic => ("the static lifetime".to_owned(), None),
145 ty::ReEmpty => ("the empty lifetime".to_owned(), None),
147 // FIXME(#13998) ReSkolemized should probably print like
148 // ReFree rather than dumping Debug output on the user.
150 // We shouldn't really be having unification failures with ReVar
151 // and ReLateBound though.
152 ty::ReSkolemized(..) | ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
153 (format!("lifetime {:?}", region), None)
156 // We shouldn't encounter an error message with ReClosureBound.
157 ty::ReClosureBound(..) => {
158 bug!("encountered unexpected ReClosureBound: {:?}", region,);
162 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
165 pub fn note_and_explain_free_region(
167 err: &mut DiagnosticBuilder,
169 region: ty::Region<'tcx>,
172 let (description, span) = self.msg_span_from_free_region(region);
174 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
177 fn msg_span_from_free_region(self, region: ty::Region<'tcx>) -> (String, Option<Span>) {
178 let scope = region.free_region_binding_scope(self);
179 let node = self.hir.as_local_node_id(scope).unwrap_or(DUMMY_NODE_ID);
181 let tag = match self.hir.find(node) {
182 Some(hir_map::NodeBlock(_)) | Some(hir_map::NodeExpr(_)) => "body",
183 Some(hir_map::NodeItem(it)) => Self::item_scope_tag(&it),
184 Some(hir_map::NodeTraitItem(it)) => Self::trait_item_scope_tag(&it),
185 Some(hir_map::NodeImplItem(it)) => Self::impl_item_scope_tag(&it),
187 // this really should not happen, but it does:
191 "unexpected node ({}) for scope {:?}. \
192 Please report a bug.",
193 self.hir.node_to_string(node),
200 "unknown node for scope {:?}. \
201 Please report a bug.",
207 let (prefix, span) = match *region {
208 ty::ReEarlyBound(ref br) => (
209 format!("the lifetime {} as defined on", br.name),
210 self.sess.codemap().def_span(self.hir.span(node)),
212 ty::ReFree(ref fr) => match fr.bound_region {
214 format!("the anonymous lifetime #{} defined on", idx + 1),
218 "an anonymous lifetime defined on".to_owned(),
222 format!("the lifetime {} as defined on", fr.bound_region),
223 self.sess.codemap().def_span(self.hir.span(node)),
228 let (msg, opt_span) = self.explain_span(tag, span);
229 (format!("{} {}", prefix, msg), opt_span)
233 err: &mut DiagnosticBuilder,
239 let message = format!("{}{}{}", prefix, description, suffix);
241 if let Some(span) = span {
242 err.span_note(span, &message);
248 fn item_scope_tag(item: &hir::Item) -> &'static str {
250 hir::ItemImpl(..) => "impl",
251 hir::ItemStruct(..) => "struct",
252 hir::ItemUnion(..) => "union",
253 hir::ItemEnum(..) => "enum",
254 hir::ItemTrait(..) => "trait",
255 hir::ItemFn(..) => "function body",
260 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
262 hir::TraitItemKind::Method(..) => "method body",
263 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
267 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
269 hir::ImplItemKind::Method(..) => "method body",
270 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Type(_) => "associated item",
274 fn explain_span(self, heading: &str, span: Span) -> (String, Option<Span>) {
275 let lo = self.sess.codemap().lookup_char_pos_adj(span.lo());
277 format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
283 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
284 pub fn report_region_errors(
286 region_scope_tree: ®ion::ScopeTree,
287 errors: &Vec<RegionResolutionError<'tcx>>,
288 will_later_be_reported_by_nll: bool,
290 debug!("report_region_errors(): {} errors to start", errors.len());
292 if will_later_be_reported_by_nll && self.tcx.nll() {
293 // With `#![feature(nll)]`, we want to present a nice user
294 // experience, so don't even mention the errors from the
296 if self.tcx.features().nll {
300 // But with -Znll, it's nice to have some note for later.
301 for error in errors {
303 RegionResolutionError::ConcreteFailure(ref origin, ..)
304 | RegionResolutionError::GenericBoundFailure(ref origin, ..) => {
307 .span_warn(origin.span(), "not reporting region error due to -Znll");
310 RegionResolutionError::SubSupConflict(ref rvo, ..) => {
313 .span_warn(rvo.span(), "not reporting region error due to -Znll");
321 // try to pre-process the errors, which will group some of them
322 // together into a `ProcessedErrors` group:
323 let errors = self.process_errors(errors);
326 "report_region_errors: {} errors after preprocessing",
330 for error in errors {
331 debug!("report_region_errors: error = {:?}", error);
333 if !self.try_report_nice_region_error(&error) {
334 match error.clone() {
335 // These errors could indicate all manner of different
336 // problems with many different solutions. Rather
337 // than generate a "one size fits all" error, what we
338 // attempt to do is go through a number of specific
339 // scenarios and try to find the best way to present
340 // the error. If all of these fails, we fall back to a rather
341 // general bit of code that displays the error information
342 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
343 self.report_concrete_failure(region_scope_tree, origin, sub, sup)
347 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
348 self.report_generic_bound_failure(
357 RegionResolutionError::SubSupConflict(
364 self.report_sub_sup_conflict(
378 // This method goes through all the errors and try to group certain types
379 // of error together, for the purpose of suggesting explicit lifetime
380 // parameters to the user. This is done so that we can have a more
381 // complete view of what lifetimes should be the same.
382 // If the return value is an empty vector, it means that processing
383 // failed (so the return value of this method should not be used).
385 // The method also attempts to weed out messages that seem like
386 // duplicates that will be unhelpful to the end-user. But
387 // obviously it never weeds out ALL errors.
390 errors: &Vec<RegionResolutionError<'tcx>>,
391 ) -> Vec<RegionResolutionError<'tcx>> {
392 debug!("process_errors()");
394 // We want to avoid reporting generic-bound failures if we can
395 // avoid it: these have a very high rate of being unhelpful in
396 // practice. This is because they are basically secondary
397 // checks that test the state of the region graph after the
398 // rest of inference is done, and the other kinds of errors
399 // indicate that the region constraint graph is internally
400 // inconsistent, so these test results are likely to be
403 // Therefore, we filter them out of the list unless they are
404 // the only thing in the list.
406 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
407 RegionResolutionError::GenericBoundFailure(..) => true,
408 RegionResolutionError::ConcreteFailure(..)
409 | RegionResolutionError::SubSupConflict(..) => false,
412 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
417 .filter(|&e| !is_bound_failure(e))
422 // sort the errors by span, for better error message stability.
423 errors.sort_by_key(|u| match *u {
424 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
425 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
426 RegionResolutionError::SubSupConflict(ref rvo, _, _, _, _) => rvo.span(),
431 /// Adds a note if the types come from similarly named crates
432 fn check_and_note_conflicting_crates(
434 err: &mut DiagnosticBuilder,
435 terr: &TypeError<'tcx>,
438 let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
439 // Only external crates, if either is from a local
440 // module we could have false positives
441 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
442 let exp_path = self.tcx.item_path_str(did1);
443 let found_path = self.tcx.item_path_str(did2);
444 let exp_abs_path = self.tcx.absolute_item_path_str(did1);
445 let found_abs_path = self.tcx.absolute_item_path_str(did2);
446 // We compare strings because DefPath can be different
447 // for imported and non-imported crates
448 if exp_path == found_path || exp_abs_path == found_abs_path {
449 let crate_name = self.tcx.crate_name(did1.krate);
453 "Perhaps two different versions \
454 of crate `{}` are being used?",
462 TypeError::Sorts(ref exp_found) => {
463 // if they are both "path types", there's a chance of ambiguity
464 // due to different versions of the same crate
465 match (&exp_found.expected.sty, &exp_found.found.sty) {
466 (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
467 report_path_match(err, exp_adt.did, found_adt.did);
472 TypeError::Traits(ref exp_found) => {
473 report_path_match(err, exp_found.expected, exp_found.found);
475 _ => (), // FIXME(#22750) handle traits and stuff
479 fn note_error_origin(&self, err: &mut DiagnosticBuilder<'tcx>, cause: &ObligationCause<'tcx>) {
481 ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
482 hir::MatchSource::IfLetDesugar { .. } => {
483 let msg = "`if let` arm with an incompatible type";
484 if self.tcx.sess.codemap().is_multiline(arm_span) {
485 err.span_note(arm_span, msg);
487 err.span_label(arm_span, msg);
491 let msg = "match arm with an incompatible type";
492 if self.tcx.sess.codemap().is_multiline(arm_span) {
493 err.span_note(arm_span, msg);
495 err.span_label(arm_span, msg);
503 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
504 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
505 /// populate `other_value` with `other_ty`.
509 /// ^^^^--------^ this is highlighted
511 /// | this type argument is exactly the same as the other type, not highlighted
512 /// this is highlighted
514 /// -------- this type is the same as a type argument in the other type, not highlighted
518 value: &mut DiagnosticStyledString,
519 other_value: &mut DiagnosticStyledString,
521 sub: &ty::subst::Substs<'tcx>,
525 // `value` and `other_value` hold two incomplete type representation for display.
526 // `name` is the path of both types being compared. `sub`
527 value.push_highlighted(name);
530 value.push_highlighted("<");
533 // Output the lifetimes fot the first type
534 let lifetimes = sub.regions()
536 let s = format!("{}", lifetime);
545 if !lifetimes.is_empty() {
546 if sub.regions().count() < len {
547 value.push_normal(lifetimes + &", ");
549 value.push_normal(lifetimes);
553 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
554 // `pos` and `other_ty`.
555 for (i, type_arg) in sub.types().enumerate() {
557 let values = self.cmp(type_arg, other_ty);
558 value.0.extend((values.0).0);
559 other_value.0.extend((values.1).0);
561 value.push_highlighted(format!("{}", type_arg));
564 if len > 0 && i != len - 1 {
565 value.push_normal(", ");
567 //self.push_comma(&mut value, &mut other_value, len, i);
570 value.push_highlighted(">");
574 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
575 /// as that is the difference to the other type.
577 /// For the following code:
580 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
583 /// The type error output will behave in the following way:
587 /// ^^^^--------^ this is highlighted
589 /// | this type argument is exactly the same as the other type, not highlighted
590 /// this is highlighted
592 /// -------- this type is the same as a type argument in the other type, not highlighted
596 mut t1_out: &mut DiagnosticStyledString,
597 mut t2_out: &mut DiagnosticStyledString,
599 sub: &ty::subst::Substs<'tcx>,
603 for (i, ta) in sub.types().enumerate() {
605 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
608 if let &ty::TyAdt(def, _) = &ta.sty {
609 let path_ = self.tcx.item_path_str(def.did.clone());
610 if path_ == other_path {
611 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
619 /// Add a `,` to the type representation only if it is appropriate.
622 value: &mut DiagnosticStyledString,
623 other_value: &mut DiagnosticStyledString,
627 if len > 0 && pos != len - 1 {
628 value.push_normal(", ");
629 other_value.push_normal(", ");
633 /// Compare two given types, eliding parts that are the same between them and highlighting
634 /// relevant differences, and return two representation of those types for highlighted printing.
635 fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
636 fn equals<'tcx>(a: &Ty<'tcx>, b: &Ty<'tcx>) -> bool {
637 match (&a.sty, &b.sty) {
638 (a, b) if *a == *b => true,
639 (&ty::TyInt(_), &ty::TyInfer(ty::InferTy::IntVar(_)))
640 | (&ty::TyInfer(ty::InferTy::IntVar(_)), &ty::TyInt(_))
641 | (&ty::TyInfer(ty::InferTy::IntVar(_)), &ty::TyInfer(ty::InferTy::IntVar(_)))
642 | (&ty::TyFloat(_), &ty::TyInfer(ty::InferTy::FloatVar(_)))
643 | (&ty::TyInfer(ty::InferTy::FloatVar(_)), &ty::TyFloat(_))
645 &ty::TyInfer(ty::InferTy::FloatVar(_)),
646 &ty::TyInfer(ty::InferTy::FloatVar(_)),
652 fn push_ty_ref<'tcx>(
653 r: &ty::Region<'tcx>,
654 tnm: &ty::TypeAndMut<'tcx>,
655 s: &mut DiagnosticStyledString,
657 let r = &format!("{}", r);
658 s.push_highlighted(format!(
661 if r == "" { "" } else { " " },
662 if tnm.mutbl == hir::MutMutable {
668 s.push_normal(format!("{}", tnm.ty));
671 match (&t1.sty, &t2.sty) {
672 (&ty::TyAdt(def1, sub1), &ty::TyAdt(def2, sub2)) => {
673 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
674 let path1 = self.tcx.item_path_str(def1.did.clone());
675 let path2 = self.tcx.item_path_str(def2.did.clone());
676 if def1.did == def2.did {
677 // Easy case. Replace same types with `_` to shorten the output and highlight
678 // the differing ones.
679 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
682 // --- ^ type argument elided
684 // highlighted in output
685 values.0.push_normal(path1);
686 values.1.push_normal(path2);
688 // Only draw `<...>` if there're lifetime/type arguments.
689 let len = sub1.len();
691 values.0.push_normal("<");
692 values.1.push_normal("<");
695 fn lifetime_display(lifetime: Region) -> String {
696 let s = format!("{}", lifetime);
703 // At one point we'd like to elide all lifetimes here, they are irrelevant for
704 // all diagnostics that use this output
708 // ^^ ^^ --- type arguments are not elided
710 // | elided as they were the same
711 // not elided, they were different, but irrelevant
712 let lifetimes = sub1.regions().zip(sub2.regions());
713 for (i, lifetimes) in lifetimes.enumerate() {
714 let l1 = lifetime_display(lifetimes.0);
715 let l2 = lifetime_display(lifetimes.1);
717 values.0.push_normal("'_");
718 values.1.push_normal("'_");
720 values.0.push_highlighted(l1);
721 values.1.push_highlighted(l2);
723 self.push_comma(&mut values.0, &mut values.1, len, i);
726 // We're comparing two types with the same path, so we compare the type
727 // arguments for both. If they are the same, do not highlight and elide from the
731 // ^ elided type as this type argument was the same in both sides
732 let type_arguments = sub1.types().zip(sub2.types());
733 let regions_len = sub1.regions().collect::<Vec<_>>().len();
734 for (i, (ta1, ta2)) in type_arguments.enumerate() {
735 let i = i + regions_len;
737 values.0.push_normal("_");
738 values.1.push_normal("_");
740 let (x1, x2) = self.cmp(ta1, ta2);
741 (values.0).0.extend(x1.0);
742 (values.1).0.extend(x2.0);
744 self.push_comma(&mut values.0, &mut values.1, len, i);
747 // Close the type argument bracket.
748 // Only draw `<...>` if there're lifetime/type arguments.
750 values.0.push_normal(">");
751 values.1.push_normal(">");
756 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
758 // ------- this type argument is exactly the same as the other type
760 if self.cmp_type_arg(
772 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
775 // ------- this type argument is exactly the same as the other type
776 if self.cmp_type_arg(&mut values.1, &mut values.0, path2, sub2, path1, &t1)
782 // We couldn't find anything in common, highlight everything.
783 // let x: Bar<Qux> = y::<Foo<Zar>>();
785 DiagnosticStyledString::highlighted(format!("{}", t1)),
786 DiagnosticStyledString::highlighted(format!("{}", t2)),
791 // When finding T != &T, highlight only the borrow
792 (&ty::TyRef(r1, ref tnm1), _) if equals(&tnm1.ty, &t2) => {
793 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
794 push_ty_ref(&r1, tnm1, &mut values.0);
795 values.1.push_normal(format!("{}", t2));
798 (_, &ty::TyRef(r2, ref tnm2)) if equals(&t1, &tnm2.ty) => {
799 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
800 values.0.push_normal(format!("{}", t1));
801 push_ty_ref(&r2, tnm2, &mut values.1);
805 // When encountering &T != &mut T, highlight only the borrow
806 (&ty::TyRef(r1, ref tnm1), &ty::TyRef(r2, ref tnm2)) if equals(&tnm1.ty, &tnm2.ty) => {
807 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
808 push_ty_ref(&r1, tnm1, &mut values.0);
809 push_ty_ref(&r2, tnm2, &mut values.1);
815 // The two types are the same, elide and don't highlight.
817 DiagnosticStyledString::normal("_"),
818 DiagnosticStyledString::normal("_"),
821 // We couldn't find anything in common, highlight everything.
823 DiagnosticStyledString::highlighted(format!("{}", t1)),
824 DiagnosticStyledString::highlighted(format!("{}", t2)),
831 pub fn note_type_err(
833 diag: &mut DiagnosticBuilder<'tcx>,
834 cause: &ObligationCause<'tcx>,
835 secondary_span: Option<(Span, String)>,
836 mut values: Option<ValuePairs<'tcx>>,
837 terr: &TypeError<'tcx>,
839 // For some types of errors, expected-found does not make
840 // sense, so just ignore the values we were given.
842 TypeError::CyclicTy(_) => {
848 let (expected_found, exp_found, is_simple_error) = match values {
849 None => (None, None, false),
851 let (is_simple_error, exp_found) = match values {
852 ValuePairs::Types(exp_found) => {
854 exp_found.expected.is_primitive() && exp_found.found.is_primitive();
856 (is_simple_err, Some(exp_found))
860 let vals = match self.values_str(&values) {
861 Some((expected, found)) => Some((expected, found)),
863 // Derived error. Cancel the emitter.
864 self.tcx.sess.diagnostic().cancel(diag);
868 (vals, exp_found, is_simple_error)
872 let span = cause.span(&self.tcx);
874 diag.span_label(span, terr.to_string());
875 if let Some((sp, msg)) = secondary_span {
876 diag.span_label(sp, msg);
879 if let Some((expected, found)) = expected_found {
880 match (terr, is_simple_error, expected == found) {
881 (&TypeError::Sorts(ref values), false, true) => {
882 diag.note_expected_found_extra(
886 &format!(" ({})", values.expected.sort_string(self.tcx)),
887 &format!(" ({})", values.found.sort_string(self.tcx)),
891 if let Some(exp_found) = exp_found {
892 let (def_id, ret_ty) = match exp_found.found.sty {
893 TypeVariants::TyFnDef(def, _) => {
894 (Some(def), Some(self.tcx.fn_sig(def).output()))
899 let exp_is_struct = match exp_found.expected.sty {
900 TypeVariants::TyAdt(def, _) => def.is_struct(),
904 if let (Some(def_id), Some(ret_ty)) = (def_id, ret_ty) {
905 if exp_is_struct && exp_found.expected == ret_ty.0 {
906 let message = format!(
907 "did you mean `{}(/* fields */)`?",
908 self.tcx.item_path_str(def_id)
910 diag.span_label(span, message);
915 diag.note_expected_found(&"type", expected, found);
921 self.check_and_note_conflicting_crates(diag, terr, span);
922 self.tcx.note_and_explain_type_err(diag, terr, span);
924 // It reads better to have the error origin as the final
926 self.note_error_origin(diag, &cause);
929 pub fn report_and_explain_type_error(
931 trace: TypeTrace<'tcx>,
932 terr: &TypeError<'tcx>,
933 ) -> DiagnosticBuilder<'tcx> {
935 "report_and_explain_type_error(trace={:?}, terr={:?})",
939 let span = trace.cause.span(&self.tcx);
940 let failure_code = trace.cause.as_failure_code(terr);
941 let mut diag = match failure_code {
942 FailureCode::Error0317(failure_str) => {
943 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
945 FailureCode::Error0580(failure_str) => {
946 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
948 FailureCode::Error0308(failure_str) => {
949 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
951 FailureCode::Error0644(failure_str) => {
952 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
955 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
961 values: &ValuePairs<'tcx>,
962 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
964 infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
965 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
966 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
970 fn expected_found_str_ty(
972 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
973 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
974 let exp_found = self.resolve_type_vars_if_possible(exp_found);
975 if exp_found.references_error() {
979 Some(self.cmp(exp_found.expected, exp_found.found))
982 /// Returns a string of the form "expected `{}`, found `{}`".
983 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
985 exp_found: &ty::error::ExpectedFound<T>,
986 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
987 let exp_found = self.resolve_type_vars_if_possible(exp_found);
988 if exp_found.references_error() {
993 DiagnosticStyledString::highlighted(format!("{}", exp_found.expected)),
994 DiagnosticStyledString::highlighted(format!("{}", exp_found.found)),
998 pub fn report_generic_bound_failure(
1000 region_scope_tree: ®ion::ScopeTree,
1002 origin: Option<SubregionOrigin<'tcx>>,
1003 bound_kind: GenericKind<'tcx>,
1006 // Attempt to obtain the span of the parameter so we can
1007 // suggest adding an explicit lifetime bound to it.
1008 let type_param_span = match (self.in_progress_tables, bound_kind) {
1009 (Some(ref table), GenericKind::Param(ref param)) => {
1010 let table = table.borrow();
1011 table.local_id_root.and_then(|did| {
1012 let generics = self.tcx.generics_of(did);
1013 // Account for the case where `did` corresponds to `Self`, which doesn't have
1014 // the expected type argument.
1015 if !param.is_self() {
1016 let type_param = generics.type_param(param, self.tcx);
1017 let hir = &self.tcx.hir;
1018 hir.as_local_node_id(type_param.def_id).map(|id| {
1019 // Get the `hir::TyParam` to verify whether it already has any bounds.
1020 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1021 // instead we suggest `T: 'a + 'b` in that case.
1022 let has_lifetimes = if let hir_map::NodeTyParam(ref p) = hir.get(id) {
1027 let sp = hir.span(id);
1028 // `sp` only covers `T`, change it so that it covers
1029 // `T:` when appropriate
1030 let sp = if has_lifetimes {
1034 .next_point(self.tcx.sess.codemap().next_point(sp)))
1048 let labeled_user_string = match bound_kind {
1049 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1050 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1053 if let Some(SubregionOrigin::CompareImplMethodObligation {
1060 self.report_extra_impl_obligation(
1065 &format!("`{}: {}`", bound_kind, sub),
1070 fn binding_suggestion<'tcx, S: fmt::Display>(
1071 err: &mut DiagnosticBuilder<'tcx>,
1072 type_param_span: Option<(Span, bool)>,
1073 bound_kind: GenericKind<'tcx>,
1076 let consider = &format!(
1077 "consider adding an explicit lifetime bound `{}: {}`...",
1080 if let Some((sp, has_lifetimes)) = type_param_span {
1081 let tail = if has_lifetimes { " + " } else { "" };
1082 let suggestion = format!("{}: {}{}", bound_kind, sub, tail);
1083 err.span_suggestion_short(sp, consider, suggestion);
1089 let mut err = match *sub {
1091 | ty::ReFree(ty::FreeRegion {
1092 bound_region: ty::BrNamed(..),
1095 // Does the required lifetime have a nice name we can print?
1096 let mut err = struct_span_err!(
1100 "{} may not live long enough",
1103 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1108 // Does the required lifetime have a nice name we can print?
1109 let mut err = struct_span_err!(
1113 "{} may not live long enough",
1116 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1121 // If not, be less specific.
1122 let mut err = struct_span_err!(
1126 "{} may not live long enough",
1130 "consider adding an explicit lifetime bound for `{}`",
1133 self.tcx.note_and_explain_region(
1136 &format!("{} must be valid for ", labeled_user_string),
1144 if let Some(origin) = origin {
1145 self.note_region_origin(&mut err, &origin);
1150 fn report_sub_sup_conflict(
1152 region_scope_tree: ®ion::ScopeTree,
1153 var_origin: RegionVariableOrigin,
1154 sub_origin: SubregionOrigin<'tcx>,
1155 sub_region: Region<'tcx>,
1156 sup_origin: SubregionOrigin<'tcx>,
1157 sup_region: Region<'tcx>,
1159 let mut err = self.report_inference_failure(var_origin);
1161 self.tcx.note_and_explain_region(
1164 "first, the lifetime cannot outlive ",
1169 match (&sup_origin, &sub_origin) {
1170 (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1171 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1172 self.values_str(&sup_trace.values),
1173 self.values_str(&sub_trace.values),
1175 if sub_expected == sup_expected && sub_found == sup_found {
1176 self.tcx.note_and_explain_region(
1179 "...but the lifetime must also be valid for ",
1184 "...so that the {}:\nexpected {}\n found {}",
1185 sup_trace.cause.as_requirement_str(),
1186 sup_expected.content(),
1197 self.note_region_origin(&mut err, &sup_origin);
1199 self.tcx.note_and_explain_region(
1202 "but, the lifetime must be valid for ",
1207 self.note_region_origin(&mut err, &sub_origin);
1212 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1213 fn report_inference_failure(
1215 var_origin: RegionVariableOrigin,
1216 ) -> DiagnosticBuilder<'tcx> {
1217 let br_string = |br: ty::BoundRegion| {
1218 let mut s = br.to_string();
1224 let var_description = match var_origin {
1225 infer::MiscVariable(_) => "".to_string(),
1226 infer::PatternRegion(_) => " for pattern".to_string(),
1227 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1228 infer::Autoref(_) => " for autoref".to_string(),
1229 infer::Coercion(_) => " for automatic coercion".to_string(),
1230 infer::LateBoundRegion(_, br, infer::FnCall) => {
1231 format!(" for lifetime parameter {}in function call", br_string(br))
1233 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1234 format!(" for lifetime parameter {}in generic type", br_string(br))
1236 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1237 " for lifetime parameter {}in trait containing associated type `{}`",
1239 self.tcx.associated_item(def_id).name
1241 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1242 infer::BoundRegionInCoherence(name) => {
1243 format!(" for lifetime parameter `{}` in coherence check", name)
1245 infer::UpvarRegion(ref upvar_id, _) => {
1246 let var_node_id = self.tcx.hir.hir_to_node_id(upvar_id.var_id);
1247 let var_name = self.tcx.hir.name(var_node_id);
1248 format!(" for capture of `{}` by closure", var_name)
1250 infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1257 "cannot infer an appropriate lifetime{} \
1258 due to conflicting requirements",
1265 Error0317(&'static str),
1266 Error0580(&'static str),
1267 Error0308(&'static str),
1268 Error0644(&'static str),
1271 impl<'tcx> ObligationCause<'tcx> {
1272 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1273 use self::FailureCode::*;
1274 use traits::ObligationCauseCode::*;
1276 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1277 MatchExpressionArm { source, .. } => Error0308(match source {
1278 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have incompatible types",
1279 _ => "match arms have incompatible types",
1281 IfExpression => Error0308("if and else have incompatible types"),
1282 IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1283 EquatePredicate => Error0308("equality predicate not satisfied"),
1284 MainFunctionType => Error0580("main function has wrong type"),
1285 StartFunctionType => Error0308("start function has wrong type"),
1286 IntrinsicType => Error0308("intrinsic has wrong type"),
1287 MethodReceiver => Error0308("mismatched method receiver"),
1289 // In the case where we have no more specific thing to
1290 // say, also take a look at the error code, maybe we can
1293 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1294 Error0644("closure/generator type that references itself")
1296 _ => Error0308("mismatched types"),
1301 fn as_requirement_str(&self) -> &'static str {
1302 use traits::ObligationCauseCode::*;
1304 CompareImplMethodObligation { .. } => "method type is compatible with trait",
1305 ExprAssignable => "expression is assignable",
1306 MatchExpressionArm { source, .. } => match source {
1307 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1308 _ => "match arms have compatible types",
1310 IfExpression => "if and else have compatible types",
1311 IfExpressionWithNoElse => "if missing an else returns ()",
1312 EquatePredicate => "equality where clause is satisfied",
1313 MainFunctionType => "`main` function has the correct type",
1314 StartFunctionType => "`start` function has the correct type",
1315 IntrinsicType => "intrinsic has the correct type",
1316 MethodReceiver => "method receiver has the correct type",
1317 _ => "types are compatible",