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(_) | ty::ReStatic => {
142 self.msg_span_from_free_region(region)
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::ReCanonical(..) |
158 ty::ReClosureBound(..) => {
159 bug!("encountered unexpected ReClosureBound: {:?}", region,);
163 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
166 pub fn note_and_explain_free_region(
168 err: &mut DiagnosticBuilder,
170 region: ty::Region<'tcx>,
173 let (description, span) = self.msg_span_from_free_region(region);
175 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
178 fn msg_span_from_free_region(self, region: ty::Region<'tcx>) -> (String, Option<Span>) {
180 ty::ReEarlyBound(_) | ty::ReFree(_) => {
181 self.msg_span_from_early_bound_and_free_regions(region)
183 ty::ReStatic => ("the static lifetime".to_owned(), None),
184 _ => bug!("{:?}", region),
188 fn msg_span_from_early_bound_and_free_regions(
190 region: ty::Region<'tcx>,
191 ) -> (String, Option<Span>) {
192 let scope = region.free_region_binding_scope(self);
193 let node = self.hir.as_local_node_id(scope).unwrap_or(DUMMY_NODE_ID);
195 let tag = match self.hir.find(node) {
196 Some(hir_map::NodeBlock(_)) | Some(hir_map::NodeExpr(_)) => "body",
197 Some(hir_map::NodeItem(it)) => Self::item_scope_tag(&it),
198 Some(hir_map::NodeTraitItem(it)) => Self::trait_item_scope_tag(&it),
199 Some(hir_map::NodeImplItem(it)) => Self::impl_item_scope_tag(&it),
201 // this really should not happen, but it does:
205 "unexpected node ({}) for scope {:?}. \
206 Please report a bug.",
207 self.hir.node_to_string(node),
214 "unknown node for scope {:?}. \
215 Please report a bug.",
221 let (prefix, span) = match *region {
222 ty::ReEarlyBound(ref br) => (
223 format!("the lifetime {} as defined on", br.name),
224 self.sess.codemap().def_span(self.hir.span(node)),
226 ty::ReFree(ref fr) => match fr.bound_region {
228 format!("the anonymous lifetime #{} defined on", idx + 1),
232 "an anonymous lifetime defined on".to_owned(),
236 format!("the lifetime {} as defined on", fr.bound_region),
237 self.sess.codemap().def_span(self.hir.span(node)),
242 let (msg, opt_span) = self.explain_span(tag, span);
243 (format!("{} {}", prefix, msg), opt_span)
247 err: &mut DiagnosticBuilder,
253 let message = format!("{}{}{}", prefix, description, suffix);
255 if let Some(span) = span {
256 err.span_note(span, &message);
262 fn item_scope_tag(item: &hir::Item) -> &'static str {
264 hir::ItemImpl(..) => "impl",
265 hir::ItemStruct(..) => "struct",
266 hir::ItemUnion(..) => "union",
267 hir::ItemEnum(..) => "enum",
268 hir::ItemTrait(..) => "trait",
269 hir::ItemFn(..) => "function body",
274 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
276 hir::TraitItemKind::Method(..) => "method body",
277 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
281 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
283 hir::ImplItemKind::Method(..) => "method body",
284 hir::ImplItemKind::Const(..) | hir::ImplItemKind::Type(_) => "associated item",
288 fn explain_span(self, heading: &str, span: Span) -> (String, Option<Span>) {
289 let lo = self.sess.codemap().lookup_char_pos_adj(span.lo());
291 format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
297 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
298 pub fn report_region_errors(
300 region_scope_tree: ®ion::ScopeTree,
301 errors: &Vec<RegionResolutionError<'tcx>>,
302 will_later_be_reported_by_nll: bool,
304 debug!("report_region_errors(): {} errors to start", errors.len());
306 if will_later_be_reported_by_nll && self.tcx.use_mir_borrowck() {
307 // With `#![feature(nll)]`, we want to present a nice user
308 // experience, so don't even mention the errors from the
310 if self.tcx.features().nll {
314 // But with nll, it's nice to have some note for later.
315 for error in errors {
317 RegionResolutionError::ConcreteFailure(ref origin, ..)
318 | RegionResolutionError::GenericBoundFailure(ref origin, ..) => {
321 .span_warn(origin.span(), "not reporting region error due to nll");
324 RegionResolutionError::SubSupConflict(ref rvo, ..) => {
327 .span_warn(rvo.span(), "not reporting region error due to nll");
335 // try to pre-process the errors, which will group some of them
336 // together into a `ProcessedErrors` group:
337 let errors = self.process_errors(errors);
340 "report_region_errors: {} errors after preprocessing",
344 for error in errors {
345 debug!("report_region_errors: error = {:?}", error);
347 if !self.try_report_nice_region_error(&error) {
348 match error.clone() {
349 // These errors could indicate all manner of different
350 // problems with many different solutions. Rather
351 // than generate a "one size fits all" error, what we
352 // attempt to do is go through a number of specific
353 // scenarios and try to find the best way to present
354 // the error. If all of these fails, we fall back to a rather
355 // general bit of code that displays the error information
356 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
357 self.report_concrete_failure(region_scope_tree, origin, sub, sup)
361 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
362 self.report_generic_bound_failure(
371 RegionResolutionError::SubSupConflict(
378 self.report_sub_sup_conflict(
392 // This method goes through all the errors and try to group certain types
393 // of error together, for the purpose of suggesting explicit lifetime
394 // parameters to the user. This is done so that we can have a more
395 // complete view of what lifetimes should be the same.
396 // If the return value is an empty vector, it means that processing
397 // failed (so the return value of this method should not be used).
399 // The method also attempts to weed out messages that seem like
400 // duplicates that will be unhelpful to the end-user. But
401 // obviously it never weeds out ALL errors.
404 errors: &Vec<RegionResolutionError<'tcx>>,
405 ) -> Vec<RegionResolutionError<'tcx>> {
406 debug!("process_errors()");
408 // We want to avoid reporting generic-bound failures if we can
409 // avoid it: these have a very high rate of being unhelpful in
410 // practice. This is because they are basically secondary
411 // checks that test the state of the region graph after the
412 // rest of inference is done, and the other kinds of errors
413 // indicate that the region constraint graph is internally
414 // inconsistent, so these test results are likely to be
417 // Therefore, we filter them out of the list unless they are
418 // the only thing in the list.
420 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
421 RegionResolutionError::GenericBoundFailure(..) => true,
422 RegionResolutionError::ConcreteFailure(..)
423 | RegionResolutionError::SubSupConflict(..) => false,
426 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
431 .filter(|&e| !is_bound_failure(e))
436 // sort the errors by span, for better error message stability.
437 errors.sort_by_key(|u| match *u {
438 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
439 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
440 RegionResolutionError::SubSupConflict(ref rvo, _, _, _, _) => rvo.span(),
445 /// Adds a note if the types come from similarly named crates
446 fn check_and_note_conflicting_crates(
448 err: &mut DiagnosticBuilder,
449 terr: &TypeError<'tcx>,
452 let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
453 // Only external crates, if either is from a local
454 // module we could have false positives
455 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
456 let exp_path = self.tcx.item_path_str(did1);
457 let found_path = self.tcx.item_path_str(did2);
458 let exp_abs_path = self.tcx.absolute_item_path_str(did1);
459 let found_abs_path = self.tcx.absolute_item_path_str(did2);
460 // We compare strings because DefPath can be different
461 // for imported and non-imported crates
462 if exp_path == found_path || exp_abs_path == found_abs_path {
463 let crate_name = self.tcx.crate_name(did1.krate);
467 "Perhaps two different versions \
468 of crate `{}` are being used?",
476 TypeError::Sorts(ref exp_found) => {
477 // if they are both "path types", there's a chance of ambiguity
478 // due to different versions of the same crate
479 match (&exp_found.expected.sty, &exp_found.found.sty) {
480 (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
481 report_path_match(err, exp_adt.did, found_adt.did);
486 TypeError::Traits(ref exp_found) => {
487 report_path_match(err, exp_found.expected, exp_found.found);
489 _ => (), // FIXME(#22750) handle traits and stuff
493 fn note_error_origin(&self, err: &mut DiagnosticBuilder<'tcx>, cause: &ObligationCause<'tcx>) {
495 ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
496 hir::MatchSource::IfLetDesugar { .. } => {
497 let msg = "`if let` arm with an incompatible type";
498 if self.tcx.sess.codemap().is_multiline(arm_span) {
499 err.span_note(arm_span, msg);
501 err.span_label(arm_span, msg);
505 let msg = "match arm with an incompatible type";
506 if self.tcx.sess.codemap().is_multiline(arm_span) {
507 err.span_note(arm_span, msg);
509 err.span_label(arm_span, msg);
517 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
518 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
519 /// populate `other_value` with `other_ty`.
523 /// ^^^^--------^ this is highlighted
525 /// | this type argument is exactly the same as the other type, not highlighted
526 /// this is highlighted
528 /// -------- this type is the same as a type argument in the other type, not highlighted
532 value: &mut DiagnosticStyledString,
533 other_value: &mut DiagnosticStyledString,
535 sub: &ty::subst::Substs<'tcx>,
539 // `value` and `other_value` hold two incomplete type representation for display.
540 // `name` is the path of both types being compared. `sub`
541 value.push_highlighted(name);
544 value.push_highlighted("<");
547 // Output the lifetimes fot the first type
548 let lifetimes = sub.regions()
550 let s = format!("{}", lifetime);
559 if !lifetimes.is_empty() {
560 if sub.regions().count() < len {
561 value.push_normal(lifetimes + &", ");
563 value.push_normal(lifetimes);
567 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
568 // `pos` and `other_ty`.
569 for (i, type_arg) in sub.types().enumerate() {
571 let values = self.cmp(type_arg, other_ty);
572 value.0.extend((values.0).0);
573 other_value.0.extend((values.1).0);
575 value.push_highlighted(format!("{}", type_arg));
578 if len > 0 && i != len - 1 {
579 value.push_normal(", ");
581 //self.push_comma(&mut value, &mut other_value, len, i);
584 value.push_highlighted(">");
588 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
589 /// as that is the difference to the other type.
591 /// For the following code:
594 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
597 /// The type error output will behave in the following way:
601 /// ^^^^--------^ this is highlighted
603 /// | this type argument is exactly the same as the other type, not highlighted
604 /// this is highlighted
606 /// -------- this type is the same as a type argument in the other type, not highlighted
610 mut t1_out: &mut DiagnosticStyledString,
611 mut t2_out: &mut DiagnosticStyledString,
613 sub: &ty::subst::Substs<'tcx>,
617 for (i, ta) in sub.types().enumerate() {
619 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
622 if let &ty::TyAdt(def, _) = &ta.sty {
623 let path_ = self.tcx.item_path_str(def.did.clone());
624 if path_ == other_path {
625 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
633 /// Add a `,` to the type representation only if it is appropriate.
636 value: &mut DiagnosticStyledString,
637 other_value: &mut DiagnosticStyledString,
641 if len > 0 && pos != len - 1 {
642 value.push_normal(", ");
643 other_value.push_normal(", ");
647 /// Compare two given types, eliding parts that are the same between them and highlighting
648 /// relevant differences, and return two representation of those types for highlighted printing.
649 fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
650 fn equals<'tcx>(a: &Ty<'tcx>, b: &Ty<'tcx>) -> bool {
651 match (&a.sty, &b.sty) {
652 (a, b) if *a == *b => true,
653 (&ty::TyInt(_), &ty::TyInfer(ty::InferTy::IntVar(_)))
654 | (&ty::TyInfer(ty::InferTy::IntVar(_)), &ty::TyInt(_))
655 | (&ty::TyInfer(ty::InferTy::IntVar(_)), &ty::TyInfer(ty::InferTy::IntVar(_)))
656 | (&ty::TyFloat(_), &ty::TyInfer(ty::InferTy::FloatVar(_)))
657 | (&ty::TyInfer(ty::InferTy::FloatVar(_)), &ty::TyFloat(_))
659 &ty::TyInfer(ty::InferTy::FloatVar(_)),
660 &ty::TyInfer(ty::InferTy::FloatVar(_)),
666 fn push_ty_ref<'tcx>(
667 r: &ty::Region<'tcx>,
669 mutbl: hir::Mutability,
670 s: &mut DiagnosticStyledString,
672 let r = &format!("{}", r);
673 s.push_highlighted(format!(
676 if r == "" { "" } else { " " },
677 if mutbl == hir::MutMutable {
683 s.push_normal(format!("{}", ty));
686 match (&t1.sty, &t2.sty) {
687 (&ty::TyAdt(def1, sub1), &ty::TyAdt(def2, sub2)) => {
688 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
689 let path1 = self.tcx.item_path_str(def1.did.clone());
690 let path2 = self.tcx.item_path_str(def2.did.clone());
691 if def1.did == def2.did {
692 // Easy case. Replace same types with `_` to shorten the output and highlight
693 // the differing ones.
694 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
697 // --- ^ type argument elided
699 // highlighted in output
700 values.0.push_normal(path1);
701 values.1.push_normal(path2);
703 // Only draw `<...>` if there're lifetime/type arguments.
704 let len = sub1.len();
706 values.0.push_normal("<");
707 values.1.push_normal("<");
710 fn lifetime_display(lifetime: Region) -> String {
711 let s = format!("{}", lifetime);
718 // At one point we'd like to elide all lifetimes here, they are irrelevant for
719 // all diagnostics that use this output
723 // ^^ ^^ --- type arguments are not elided
725 // | elided as they were the same
726 // not elided, they were different, but irrelevant
727 let lifetimes = sub1.regions().zip(sub2.regions());
728 for (i, lifetimes) in lifetimes.enumerate() {
729 let l1 = lifetime_display(lifetimes.0);
730 let l2 = lifetime_display(lifetimes.1);
732 values.0.push_normal("'_");
733 values.1.push_normal("'_");
735 values.0.push_highlighted(l1);
736 values.1.push_highlighted(l2);
738 self.push_comma(&mut values.0, &mut values.1, len, i);
741 // We're comparing two types with the same path, so we compare the type
742 // arguments for both. If they are the same, do not highlight and elide from the
746 // ^ elided type as this type argument was the same in both sides
747 let type_arguments = sub1.types().zip(sub2.types());
748 let regions_len = sub1.regions().collect::<Vec<_>>().len();
749 for (i, (ta1, ta2)) in type_arguments.enumerate() {
750 let i = i + regions_len;
752 values.0.push_normal("_");
753 values.1.push_normal("_");
755 let (x1, x2) = self.cmp(ta1, ta2);
756 (values.0).0.extend(x1.0);
757 (values.1).0.extend(x2.0);
759 self.push_comma(&mut values.0, &mut values.1, len, i);
762 // Close the type argument bracket.
763 // Only draw `<...>` if there're lifetime/type arguments.
765 values.0.push_normal(">");
766 values.1.push_normal(">");
771 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
773 // ------- this type argument is exactly the same as the other type
775 if self.cmp_type_arg(
787 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
790 // ------- this type argument is exactly the same as the other type
791 if self.cmp_type_arg(&mut values.1, &mut values.0, path2, sub2, path1, &t1)
797 // We couldn't find anything in common, highlight everything.
798 // let x: Bar<Qux> = y::<Foo<Zar>>();
800 DiagnosticStyledString::highlighted(format!("{}", t1)),
801 DiagnosticStyledString::highlighted(format!("{}", t2)),
806 // When finding T != &T, highlight only the borrow
807 (&ty::TyRef(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
808 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
809 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
810 values.1.push_normal(format!("{}", t2));
813 (_, &ty::TyRef(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
814 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
815 values.0.push_normal(format!("{}", t1));
816 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
820 // When encountering &T != &mut T, highlight only the borrow
821 (&ty::TyRef(r1, ref_ty1, mutbl1),
822 &ty::TyRef(r2, ref_ty2, mutbl2)) if equals(&ref_ty1, &ref_ty2) => {
823 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
824 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
825 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
831 // The two types are the same, elide and don't highlight.
833 DiagnosticStyledString::normal("_"),
834 DiagnosticStyledString::normal("_"),
837 // We couldn't find anything in common, highlight everything.
839 DiagnosticStyledString::highlighted(format!("{}", t1)),
840 DiagnosticStyledString::highlighted(format!("{}", t2)),
847 pub fn note_type_err(
849 diag: &mut DiagnosticBuilder<'tcx>,
850 cause: &ObligationCause<'tcx>,
851 secondary_span: Option<(Span, String)>,
852 mut values: Option<ValuePairs<'tcx>>,
853 terr: &TypeError<'tcx>,
855 // For some types of errors, expected-found does not make
856 // sense, so just ignore the values we were given.
858 TypeError::CyclicTy(_) => {
864 let (expected_found, exp_found, is_simple_error) = match values {
865 None => (None, None, false),
867 let (is_simple_error, exp_found) = match values {
868 ValuePairs::Types(exp_found) => {
870 exp_found.expected.is_primitive() && exp_found.found.is_primitive();
872 (is_simple_err, Some(exp_found))
876 let vals = match self.values_str(&values) {
877 Some((expected, found)) => Some((expected, found)),
879 // Derived error. Cancel the emitter.
880 self.tcx.sess.diagnostic().cancel(diag);
884 (vals, exp_found, is_simple_error)
888 let span = cause.span(&self.tcx);
890 diag.span_label(span, terr.to_string());
891 if let Some((sp, msg)) = secondary_span {
892 diag.span_label(sp, msg);
895 if let Some((expected, found)) = expected_found {
896 match (terr, is_simple_error, expected == found) {
897 (&TypeError::Sorts(ref values), false, true) => {
898 diag.note_expected_found_extra(
902 &format!(" ({})", values.expected.sort_string(self.tcx)),
903 &format!(" ({})", values.found.sort_string(self.tcx)),
907 if let Some(exp_found) = exp_found {
908 let (def_id, ret_ty) = match exp_found.found.sty {
909 TypeVariants::TyFnDef(def, _) => {
910 (Some(def), Some(self.tcx.fn_sig(def).output()))
915 let exp_is_struct = match exp_found.expected.sty {
916 TypeVariants::TyAdt(def, _) => def.is_struct(),
920 if let (Some(def_id), Some(ret_ty)) = (def_id, ret_ty) {
921 if exp_is_struct && &exp_found.expected == ret_ty.skip_binder() {
922 let message = format!(
923 "did you mean `{}(/* fields */)`?",
924 self.tcx.item_path_str(def_id)
926 diag.span_label(span, message);
931 diag.note_expected_found(&"type", expected, found);
937 self.check_and_note_conflicting_crates(diag, terr, span);
938 self.tcx.note_and_explain_type_err(diag, terr, span);
940 // It reads better to have the error origin as the final
942 self.note_error_origin(diag, &cause);
945 pub fn report_and_explain_type_error(
947 trace: TypeTrace<'tcx>,
948 terr: &TypeError<'tcx>,
949 ) -> DiagnosticBuilder<'tcx> {
951 "report_and_explain_type_error(trace={:?}, terr={:?})",
955 let span = trace.cause.span(&self.tcx);
956 let failure_code = trace.cause.as_failure_code(terr);
957 let mut diag = match failure_code {
958 FailureCode::Error0317(failure_str) => {
959 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
961 FailureCode::Error0580(failure_str) => {
962 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
964 FailureCode::Error0308(failure_str) => {
965 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
967 FailureCode::Error0644(failure_str) => {
968 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
971 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
977 values: &ValuePairs<'tcx>,
978 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
980 infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
981 infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
982 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
983 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
987 fn expected_found_str_ty(
989 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
990 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
991 let exp_found = self.resolve_type_vars_if_possible(exp_found);
992 if exp_found.references_error() {
996 Some(self.cmp(exp_found.expected, exp_found.found))
999 /// Returns a string of the form "expected `{}`, found `{}`".
1000 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1002 exp_found: &ty::error::ExpectedFound<T>,
1003 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1004 let exp_found = self.resolve_type_vars_if_possible(exp_found);
1005 if exp_found.references_error() {
1010 DiagnosticStyledString::highlighted(format!("{}", exp_found.expected)),
1011 DiagnosticStyledString::highlighted(format!("{}", exp_found.found)),
1015 pub fn report_generic_bound_failure(
1017 region_scope_tree: ®ion::ScopeTree,
1019 origin: Option<SubregionOrigin<'tcx>>,
1020 bound_kind: GenericKind<'tcx>,
1023 // Attempt to obtain the span of the parameter so we can
1024 // suggest adding an explicit lifetime bound to it.
1025 let type_param_span = match (self.in_progress_tables, bound_kind) {
1026 (Some(ref table), GenericKind::Param(ref param)) => {
1027 let table = table.borrow();
1028 table.local_id_root.and_then(|did| {
1029 let generics = self.tcx.generics_of(did);
1030 // Account for the case where `did` corresponds to `Self`, which doesn't have
1031 // the expected type argument.
1032 if !param.is_self() {
1033 let type_param = generics.type_param(param, self.tcx);
1034 let hir = &self.tcx.hir;
1035 hir.as_local_node_id(type_param.def_id).map(|id| {
1036 // Get the `hir::TyParam` to verify whether it already has any bounds.
1037 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1038 // instead we suggest `T: 'a + 'b` in that case.
1039 let has_lifetimes = if let hir_map::NodeTyParam(ref p) = hir.get(id) {
1044 let sp = hir.span(id);
1045 // `sp` only covers `T`, change it so that it covers
1046 // `T:` when appropriate
1047 let sp = if has_lifetimes {
1051 .next_point(self.tcx.sess.codemap().next_point(sp)))
1065 let labeled_user_string = match bound_kind {
1066 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1067 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1070 if let Some(SubregionOrigin::CompareImplMethodObligation {
1077 self.report_extra_impl_obligation(
1082 &format!("`{}: {}`", bound_kind, sub),
1087 fn binding_suggestion<'tcx, S: fmt::Display>(
1088 err: &mut DiagnosticBuilder<'tcx>,
1089 type_param_span: Option<(Span, bool)>,
1090 bound_kind: GenericKind<'tcx>,
1093 let consider = &format!(
1094 "consider adding an explicit lifetime bound `{}: {}`...",
1097 if let Some((sp, has_lifetimes)) = type_param_span {
1098 let tail = if has_lifetimes { " + " } else { "" };
1099 let suggestion = format!("{}: {}{}", bound_kind, sub, tail);
1100 err.span_suggestion_short(sp, consider, suggestion);
1106 let mut err = match *sub {
1108 | ty::ReFree(ty::FreeRegion {
1109 bound_region: ty::BrNamed(..),
1112 // Does the required lifetime have a nice name we can print?
1113 let mut err = struct_span_err!(
1117 "{} may not live long enough",
1120 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1125 // Does the required lifetime have a nice name we can print?
1126 let mut err = struct_span_err!(
1130 "{} may not live long enough",
1133 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1138 // If not, be less specific.
1139 let mut err = struct_span_err!(
1143 "{} may not live long enough",
1147 "consider adding an explicit lifetime bound for `{}`",
1150 self.tcx.note_and_explain_region(
1153 &format!("{} must be valid for ", labeled_user_string),
1161 if let Some(origin) = origin {
1162 self.note_region_origin(&mut err, &origin);
1167 fn report_sub_sup_conflict(
1169 region_scope_tree: ®ion::ScopeTree,
1170 var_origin: RegionVariableOrigin,
1171 sub_origin: SubregionOrigin<'tcx>,
1172 sub_region: Region<'tcx>,
1173 sup_origin: SubregionOrigin<'tcx>,
1174 sup_region: Region<'tcx>,
1176 let mut err = self.report_inference_failure(var_origin);
1178 self.tcx.note_and_explain_region(
1181 "first, the lifetime cannot outlive ",
1186 match (&sup_origin, &sub_origin) {
1187 (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1188 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1189 self.values_str(&sup_trace.values),
1190 self.values_str(&sub_trace.values),
1192 if sub_expected == sup_expected && sub_found == sup_found {
1193 self.tcx.note_and_explain_region(
1196 "...but the lifetime must also be valid for ",
1201 "...so that the {}:\nexpected {}\n found {}",
1202 sup_trace.cause.as_requirement_str(),
1203 sup_expected.content(),
1214 self.note_region_origin(&mut err, &sup_origin);
1216 self.tcx.note_and_explain_region(
1219 "but, the lifetime must be valid for ",
1224 self.note_region_origin(&mut err, &sub_origin);
1229 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1230 fn report_inference_failure(
1232 var_origin: RegionVariableOrigin,
1233 ) -> DiagnosticBuilder<'tcx> {
1234 let br_string = |br: ty::BoundRegion| {
1235 let mut s = br.to_string();
1241 let var_description = match var_origin {
1242 infer::MiscVariable(_) => "".to_string(),
1243 infer::PatternRegion(_) => " for pattern".to_string(),
1244 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1245 infer::Autoref(_) => " for autoref".to_string(),
1246 infer::Coercion(_) => " for automatic coercion".to_string(),
1247 infer::LateBoundRegion(_, br, infer::FnCall) => {
1248 format!(" for lifetime parameter {}in function call", br_string(br))
1250 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1251 format!(" for lifetime parameter {}in generic type", br_string(br))
1253 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1254 " for lifetime parameter {}in trait containing associated type `{}`",
1256 self.tcx.associated_item(def_id).name
1258 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1259 infer::BoundRegionInCoherence(name) => {
1260 format!(" for lifetime parameter `{}` in coherence check", name)
1262 infer::UpvarRegion(ref upvar_id, _) => {
1263 let var_node_id = self.tcx.hir.hir_to_node_id(upvar_id.var_id);
1264 let var_name = self.tcx.hir.name(var_node_id);
1265 format!(" for capture of `{}` by closure", var_name)
1267 infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1274 "cannot infer an appropriate lifetime{} \
1275 due to conflicting requirements",
1282 Error0317(&'static str),
1283 Error0580(&'static str),
1284 Error0308(&'static str),
1285 Error0644(&'static str),
1288 impl<'tcx> ObligationCause<'tcx> {
1289 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1290 use self::FailureCode::*;
1291 use traits::ObligationCauseCode::*;
1293 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1294 MatchExpressionArm { source, .. } => Error0308(match source {
1295 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have incompatible types",
1296 _ => "match arms have incompatible types",
1298 IfExpression => Error0308("if and else have incompatible types"),
1299 IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1300 MainFunctionType => Error0580("main function has wrong type"),
1301 StartFunctionType => Error0308("start function has wrong type"),
1302 IntrinsicType => Error0308("intrinsic has wrong type"),
1303 MethodReceiver => Error0308("mismatched method receiver"),
1305 // In the case where we have no more specific thing to
1306 // say, also take a look at the error code, maybe we can
1309 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1310 Error0644("closure/generator type that references itself")
1312 _ => Error0308("mismatched types"),
1317 fn as_requirement_str(&self) -> &'static str {
1318 use traits::ObligationCauseCode::*;
1320 CompareImplMethodObligation { .. } => "method type is compatible with trait",
1321 ExprAssignable => "expression is assignable",
1322 MatchExpressionArm { source, .. } => match source {
1323 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1324 _ => "match arms have compatible types",
1326 IfExpression => "if and else have compatible types",
1327 IfExpressionWithNoElse => "if missing an else returns ()",
1328 MainFunctionType => "`main` function has the correct type",
1329 StartFunctionType => "`start` function has the correct type",
1330 IntrinsicType => "intrinsic has the correct type",
1331 MethodReceiver => "method receiver has the correct type",
1332 _ => "types are compatible",