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.
58 use super::lexical_region_resolve::RegionResolutionError;
59 use super::region_constraints::GenericKind;
60 use super::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePairs};
61 use infer::{self, SuppressRegionErrors};
63 use errors::{Applicability, DiagnosticBuilder, DiagnosticStyledString};
65 use hir::def_id::DefId;
69 use syntax::ast::DUMMY_NODE_ID;
70 use syntax_pos::{Pos, Span};
71 use traits::{ObligationCause, ObligationCauseCode};
72 use ty::error::TypeError;
73 use ty::{self, subst::Subst, Region, Ty, TyCtxt, TyKind, TypeFoldable};
79 pub mod nice_region_error;
81 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
82 pub fn note_and_explain_region(
84 region_scope_tree: ®ion::ScopeTree,
85 err: &mut DiagnosticBuilder<'_>,
87 region: ty::Region<'tcx>,
90 let (description, span) = match *region {
91 ty::ReScope(scope) => {
93 let unknown_scope = || {
95 "{}unknown scope: {:?}{}. Please report a bug.",
99 let span = scope.span(self, region_scope_tree);
100 let tag = match self.hir.find(scope.node_id(self, region_scope_tree)) {
101 Some(Node::Block(_)) => "block",
102 Some(Node::Expr(expr)) => match expr.node {
103 hir::ExprKind::Call(..) => "call",
104 hir::ExprKind::MethodCall(..) => "method call",
105 hir::ExprKind::Match(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
106 hir::ExprKind::Match(.., hir::MatchSource::WhileLetDesugar) => "while let",
107 hir::ExprKind::Match(.., hir::MatchSource::ForLoopDesugar) => "for",
108 hir::ExprKind::Match(..) => "match",
111 Some(Node::Stmt(_)) => "statement",
112 Some(Node::Item(it)) => Self::item_scope_tag(&it),
113 Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
114 Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
116 err.span_note(span, &unknown_scope());
120 let scope_decorated_tag = match scope.data {
121 region::ScopeData::Node => tag,
122 region::ScopeData::CallSite => "scope of call-site for function",
123 region::ScopeData::Arguments => "scope of function body",
124 region::ScopeData::Destruction => {
125 new_string = format!("destruction scope surrounding {}", tag);
128 region::ScopeData::Remainder(first_statement_index) => {
129 new_string = format!(
130 "block suffix following statement {}",
131 first_statement_index.index()
136 self.explain_span(scope_decorated_tag, span)
139 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic => {
140 self.msg_span_from_free_region(region)
143 ty::ReEmpty => ("the empty lifetime".to_owned(), None),
145 // FIXME(#13998) RePlaceholder should probably print like
146 // ReFree rather than dumping Debug output on the user.
148 // We shouldn't really be having unification failures with ReVar
149 // and ReLateBound though.
150 ty::RePlaceholder(..) | ty::ReVar(_) | ty::ReLateBound(..) | ty::ReErased => {
151 (format!("lifetime {:?}", region), None)
154 // We shouldn't encounter an error message with ReClosureBound.
155 ty::ReClosureBound(..) => {
156 bug!("encountered unexpected ReClosureBound: {:?}", region,);
160 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
163 pub fn note_and_explain_free_region(
165 err: &mut DiagnosticBuilder<'_>,
167 region: ty::Region<'tcx>,
170 let (description, span) = self.msg_span_from_free_region(region);
172 TyCtxt::emit_msg_span(err, prefix, description, span, suffix);
175 fn msg_span_from_free_region(self, region: ty::Region<'tcx>) -> (String, Option<Span>) {
177 ty::ReEarlyBound(_) | ty::ReFree(_) => {
178 self.msg_span_from_early_bound_and_free_regions(region)
180 ty::ReStatic => ("the static lifetime".to_owned(), None),
181 _ => bug!("{:?}", region),
185 fn msg_span_from_early_bound_and_free_regions(
187 region: ty::Region<'tcx>,
188 ) -> (String, Option<Span>) {
189 let cm = self.sess.source_map();
191 let scope = region.free_region_binding_scope(self);
192 let node = self.hir.as_local_node_id(scope).unwrap_or(DUMMY_NODE_ID);
193 let tag = match self.hir.find(node) {
194 Some(Node::Block(_)) | Some(Node::Expr(_)) => "body",
195 Some(Node::Item(it)) => Self::item_scope_tag(&it),
196 Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
197 Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
200 let (prefix, span) = match *region {
201 ty::ReEarlyBound(ref br) => {
202 let mut sp = cm.def_span(self.hir.span(node));
203 if let Some(param) = self.hir
205 .and_then(|generics| generics.get_named(&br.name))
209 (format!("the lifetime {} as defined on", br.name), sp)
211 ty::ReFree(ty::FreeRegion {
212 bound_region: ty::BoundRegion::BrNamed(_, ref name),
215 let mut sp = cm.def_span(self.hir.span(node));
216 if let Some(param) = self.hir
218 .and_then(|generics| generics.get_named(&name))
222 (format!("the lifetime {} as defined on", name), sp)
224 ty::ReFree(ref fr) => match fr.bound_region {
226 format!("the anonymous lifetime #{} defined on", idx + 1),
230 "an anonymous lifetime defined on".to_owned(),
234 format!("the lifetime {} as defined on", fr.bound_region),
235 cm.def_span(self.hir.span(node)),
240 let (msg, opt_span) = self.explain_span(tag, span);
241 (format!("{} {}", prefix, msg), opt_span)
245 err: &mut DiagnosticBuilder<'_>,
251 let message = format!("{}{}{}", prefix, description, suffix);
253 if let Some(span) = span {
254 err.span_note(span, &message);
260 fn item_scope_tag(item: &hir::Item) -> &'static str {
262 hir::ItemKind::Impl(..) => "impl",
263 hir::ItemKind::Struct(..) => "struct",
264 hir::ItemKind::Union(..) => "union",
265 hir::ItemKind::Enum(..) => "enum",
266 hir::ItemKind::Trait(..) => "trait",
267 hir::ItemKind::Fn(..) => "function body",
272 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
274 hir::TraitItemKind::Method(..) => "method body",
275 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
279 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
281 hir::ImplItemKind::Method(..) => "method body",
282 hir::ImplItemKind::Const(..)
283 | hir::ImplItemKind::Existential(..)
284 | hir::ImplItemKind::Type(..) => "associated item",
288 fn explain_span(self, heading: &str, span: Span) -> (String, Option<Span>) {
289 let lo = self.sess.source_map().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 suppress: SuppressRegionErrors,
305 "report_region_errors(): {} errors to start, suppress = {:?}",
310 if suppress.suppressed() {
314 // try to pre-process the errors, which will group some of them
315 // together into a `ProcessedErrors` group:
316 let errors = self.process_errors(errors);
319 "report_region_errors: {} errors after preprocessing",
323 for error in errors {
324 debug!("report_region_errors: error = {:?}", error);
326 if !self.try_report_nice_region_error(&error) {
327 match error.clone() {
328 // These errors could indicate all manner of different
329 // problems with many different solutions. Rather
330 // than generate a "one size fits all" error, what we
331 // attempt to do is go through a number of specific
332 // scenarios and try to find the best way to present
333 // the error. If all of these fails, we fall back to a rather
334 // general bit of code that displays the error information
335 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
336 self.report_concrete_failure(region_scope_tree, origin, sub, sup)
340 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
341 self.report_generic_bound_failure(
350 RegionResolutionError::SubSupConflict(
357 self.report_sub_sup_conflict(
371 // This method goes through all the errors and try to group certain types
372 // of error together, for the purpose of suggesting explicit lifetime
373 // parameters to the user. This is done so that we can have a more
374 // complete view of what lifetimes should be the same.
375 // If the return value is an empty vector, it means that processing
376 // failed (so the return value of this method should not be used).
378 // The method also attempts to weed out messages that seem like
379 // duplicates that will be unhelpful to the end-user. But
380 // obviously it never weeds out ALL errors.
383 errors: &Vec<RegionResolutionError<'tcx>>,
384 ) -> Vec<RegionResolutionError<'tcx>> {
385 debug!("process_errors()");
387 // We want to avoid reporting generic-bound failures if we can
388 // avoid it: these have a very high rate of being unhelpful in
389 // practice. This is because they are basically secondary
390 // checks that test the state of the region graph after the
391 // rest of inference is done, and the other kinds of errors
392 // indicate that the region constraint graph is internally
393 // inconsistent, so these test results are likely to be
396 // Therefore, we filter them out of the list unless they are
397 // the only thing in the list.
399 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
400 RegionResolutionError::GenericBoundFailure(..) => true,
401 RegionResolutionError::ConcreteFailure(..)
402 | RegionResolutionError::SubSupConflict(..) => false,
405 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
410 .filter(|&e| !is_bound_failure(e))
415 // sort the errors by span, for better error message stability.
416 errors.sort_by_key(|u| match *u {
417 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
418 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
419 RegionResolutionError::SubSupConflict(ref rvo, _, _, _, _) => rvo.span(),
424 /// Adds a note if the types come from similarly named crates
425 fn check_and_note_conflicting_crates(
427 err: &mut DiagnosticBuilder<'_>,
428 terr: &TypeError<'tcx>,
431 let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
432 // Only external crates, if either is from a local
433 // module we could have false positives
434 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
435 let exp_path = self.tcx.item_path_str(did1);
436 let found_path = self.tcx.item_path_str(did2);
437 let exp_abs_path = self.tcx.absolute_item_path_str(did1);
438 let found_abs_path = self.tcx.absolute_item_path_str(did2);
439 // We compare strings because DefPath can be different
440 // for imported and non-imported crates
441 if exp_path == found_path || exp_abs_path == found_abs_path {
442 let crate_name = self.tcx.crate_name(did1.krate);
446 "Perhaps two different versions \
447 of crate `{}` are being used?",
455 TypeError::Sorts(ref exp_found) => {
456 // if they are both "path types", there's a chance of ambiguity
457 // due to different versions of the same crate
458 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _))
459 = (&exp_found.expected.sty, &exp_found.found.sty)
461 report_path_match(err, exp_adt.did, found_adt.did);
464 TypeError::Traits(ref exp_found) => {
465 report_path_match(err, exp_found.expected, exp_found.found);
467 _ => (), // FIXME(#22750) handle traits and stuff
471 fn note_error_origin(&self, err: &mut DiagnosticBuilder<'tcx>, cause: &ObligationCause<'tcx>) {
473 ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
474 hir::MatchSource::IfLetDesugar { .. } => {
475 let msg = "`if let` arm with an incompatible type";
476 if self.tcx.sess.source_map().is_multiline(arm_span) {
477 err.span_note(arm_span, msg);
479 err.span_label(arm_span, msg);
482 hir::MatchSource::TryDesugar => {}
484 let msg = "match arm with an incompatible type";
485 if self.tcx.sess.source_map().is_multiline(arm_span) {
486 err.span_note(arm_span, msg);
488 err.span_label(arm_span, msg);
496 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
497 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
498 /// populate `other_value` with `other_ty`.
502 /// ^^^^--------^ this is highlighted
504 /// | this type argument is exactly the same as the other type, not highlighted
505 /// this is highlighted
507 /// -------- this type is the same as a type argument in the other type, not highlighted
511 value: &mut DiagnosticStyledString,
512 other_value: &mut DiagnosticStyledString,
514 sub: &ty::subst::Substs<'tcx>,
518 // `value` and `other_value` hold two incomplete type representation for display.
519 // `name` is the path of both types being compared. `sub`
520 value.push_highlighted(name);
523 value.push_highlighted("<");
526 // Output the lifetimes for the first type
527 let lifetimes = sub.regions()
529 let s = lifetime.to_string();
538 if !lifetimes.is_empty() {
539 if sub.regions().count() < len {
540 value.push_normal(lifetimes + &", ");
542 value.push_normal(lifetimes);
546 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
547 // `pos` and `other_ty`.
548 for (i, type_arg) in sub.types().enumerate() {
550 let values = self.cmp(type_arg, other_ty);
551 value.0.extend((values.0).0);
552 other_value.0.extend((values.1).0);
554 value.push_highlighted(type_arg.to_string());
557 if len > 0 && i != len - 1 {
558 value.push_normal(", ");
560 //self.push_comma(&mut value, &mut other_value, len, i);
563 value.push_highlighted(">");
567 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
568 /// as that is the difference to the other type.
570 /// For the following code:
573 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
576 /// The type error output will behave in the following way:
580 /// ^^^^--------^ this is highlighted
582 /// | this type argument is exactly the same as the other type, not highlighted
583 /// this is highlighted
585 /// -------- this type is the same as a type argument in the other type, not highlighted
589 mut t1_out: &mut DiagnosticStyledString,
590 mut t2_out: &mut DiagnosticStyledString,
592 sub: &ty::subst::Substs<'tcx>,
596 for (i, ta) in sub.types().enumerate() {
598 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
601 if let &ty::Adt(def, _) = &ta.sty {
602 let path_ = self.tcx.item_path_str(def.did.clone());
603 if path_ == other_path {
604 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
612 /// Add a `,` to the type representation only if it is appropriate.
615 value: &mut DiagnosticStyledString,
616 other_value: &mut DiagnosticStyledString,
620 if len > 0 && pos != len - 1 {
621 value.push_normal(", ");
622 other_value.push_normal(", ");
626 /// For generic types with parameters with defaults, remove the parameters corresponding to
627 /// the defaults. This repeats a lot of the logic found in `PrintContext::parameterized`.
628 fn strip_generic_default_params(
631 substs: &ty::subst::Substs<'tcx>,
632 ) -> &'tcx ty::subst::Substs<'tcx> {
633 let generics = self.tcx.generics_of(def_id);
634 let mut num_supplied_defaults = 0;
635 let mut type_params = generics
639 .filter_map(|param| match param.kind {
640 ty::GenericParamDefKind::Lifetime => None,
641 ty::GenericParamDefKind::Type { has_default, .. } => {
642 Some((param.def_id, has_default))
647 let has_default = type_params.peek().map(|(_, has_default)| has_default);
648 *has_default.unwrap_or(&false)
651 let types = substs.types().rev();
652 for ((def_id, has_default), actual) in type_params.zip(types) {
656 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
659 num_supplied_defaults += 1;
662 let len = generics.params.len();
663 let mut generics = generics.clone();
664 generics.params.truncate(len - num_supplied_defaults);
665 substs.truncate_to(self.tcx, &generics)
668 /// Compare two given types, eliding parts that are the same between them and highlighting
669 /// relevant differences, and return two representation of those types for highlighted printing.
670 fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
671 fn equals<'tcx>(a: &Ty<'tcx>, b: &Ty<'tcx>) -> bool {
672 match (&a.sty, &b.sty) {
673 (a, b) if *a == *b => true,
674 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
675 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_))
676 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Infer(ty::InferTy::IntVar(_)))
677 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
678 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Float(_))
679 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Infer(ty::InferTy::FloatVar(_))) => {
686 fn push_ty_ref<'tcx>(
687 r: &ty::Region<'tcx>,
689 mutbl: hir::Mutability,
690 s: &mut DiagnosticStyledString,
692 let r = &r.to_string();
693 s.push_highlighted(format!(
696 if r == "" { "" } else { " " },
697 if mutbl == hir::MutMutable { "mut " } else { "" }
699 s.push_normal(ty.to_string());
702 match (&t1.sty, &t2.sty) {
703 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
704 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
705 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
706 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
707 let path1 = self.tcx.item_path_str(def1.did.clone());
708 let path2 = self.tcx.item_path_str(def2.did.clone());
709 if def1.did == def2.did {
710 // Easy case. Replace same types with `_` to shorten the output and highlight
711 // the differing ones.
712 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
715 // --- ^ type argument elided
717 // highlighted in output
718 values.0.push_normal(path1);
719 values.1.push_normal(path2);
721 // Avoid printing out default generic parameters that are common to both
723 let len1 = sub_no_defaults_1.len();
724 let len2 = sub_no_defaults_2.len();
725 let common_len = cmp::min(len1, len2);
726 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
727 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
728 let common_default_params = remainder1
731 .zip(remainder2.iter().rev())
732 .filter(|(a, b)| a == b)
734 let len = sub1.len() - common_default_params;
736 // Only draw `<...>` if there're lifetime/type arguments.
738 values.0.push_normal("<");
739 values.1.push_normal("<");
742 fn lifetime_display(lifetime: Region<'_>) -> String {
743 let s = lifetime.to_string();
750 // At one point we'd like to elide all lifetimes here, they are irrelevant for
751 // all diagnostics that use this output
755 // ^^ ^^ --- type arguments are not elided
757 // | elided as they were the same
758 // not elided, they were different, but irrelevant
759 let lifetimes = sub1.regions().zip(sub2.regions());
760 for (i, lifetimes) in lifetimes.enumerate() {
761 let l1 = lifetime_display(lifetimes.0);
762 let l2 = lifetime_display(lifetimes.1);
764 values.0.push_normal("'_");
765 values.1.push_normal("'_");
767 values.0.push_highlighted(l1);
768 values.1.push_highlighted(l2);
770 self.push_comma(&mut values.0, &mut values.1, len, i);
773 // We're comparing two types with the same path, so we compare the type
774 // arguments for both. If they are the same, do not highlight and elide from the
778 // ^ elided type as this type argument was the same in both sides
779 let type_arguments = sub1.types().zip(sub2.types());
780 let regions_len = sub1.regions().count();
781 for (i, (ta1, ta2)) in type_arguments.take(len).enumerate() {
782 let i = i + regions_len;
784 values.0.push_normal("_");
785 values.1.push_normal("_");
787 let (x1, x2) = self.cmp(ta1, ta2);
788 (values.0).0.extend(x1.0);
789 (values.1).0.extend(x2.0);
791 self.push_comma(&mut values.0, &mut values.1, len, i);
794 // Close the type argument bracket.
795 // Only draw `<...>` if there're lifetime/type arguments.
797 values.0.push_normal(">");
798 values.1.push_normal(">");
803 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
805 // ------- this type argument is exactly the same as the other type
807 if self.cmp_type_arg(
819 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
822 // ------- this type argument is exactly the same as the other type
823 if self.cmp_type_arg(
835 // We couldn't find anything in common, highlight everything.
836 // let x: Bar<Qux> = y::<Foo<Zar>>();
838 DiagnosticStyledString::highlighted(t1.to_string()),
839 DiagnosticStyledString::highlighted(t2.to_string()),
844 // When finding T != &T, highlight only the borrow
845 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
846 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
847 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
848 values.1.push_normal(t2.to_string());
851 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
852 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
853 values.0.push_normal(t1.to_string());
854 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
858 // When encountering &T != &mut T, highlight only the borrow
859 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
860 if equals(&ref_ty1, &ref_ty2) =>
862 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
863 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
864 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
870 // The two types are the same, elide and don't highlight.
872 DiagnosticStyledString::normal("_"),
873 DiagnosticStyledString::normal("_"),
876 // We couldn't find anything in common, highlight everything.
878 DiagnosticStyledString::highlighted(t1.to_string()),
879 DiagnosticStyledString::highlighted(t2.to_string()),
886 pub fn note_type_err(
888 diag: &mut DiagnosticBuilder<'tcx>,
889 cause: &ObligationCause<'tcx>,
890 secondary_span: Option<(Span, String)>,
891 mut values: Option<ValuePairs<'tcx>>,
892 terr: &TypeError<'tcx>,
894 // For some types of errors, expected-found does not make
895 // sense, so just ignore the values we were given.
897 TypeError::CyclicTy(_) => {
903 let (expected_found, exp_found, is_simple_error) = match values {
904 None => (None, None, false),
906 let (is_simple_error, exp_found) = match values {
907 ValuePairs::Types(exp_found) => {
909 exp_found.expected.is_primitive() && exp_found.found.is_primitive();
911 (is_simple_err, Some(exp_found))
915 let vals = match self.values_str(&values) {
916 Some((expected, found)) => Some((expected, found)),
918 // Derived error. Cancel the emitter.
919 self.tcx.sess.diagnostic().cancel(diag);
923 (vals, exp_found, is_simple_error)
927 let span = cause.span(&self.tcx);
929 diag.span_label(span, terr.to_string());
930 if let Some((sp, msg)) = secondary_span {
931 diag.span_label(sp, msg);
934 if let Some((expected, found)) = expected_found {
935 match (terr, is_simple_error, expected == found) {
936 (&TypeError::Sorts(ref values), false, true) => {
937 diag.note_expected_found_extra(
941 &format!(" ({})", values.expected.sort_string(self.tcx)),
942 &format!(" ({})", values.found.sort_string(self.tcx)),
946 if let Some(exp_found) = exp_found {
947 let (def_id, ret_ty) = match exp_found.found.sty {
948 TyKind::FnDef(def, _) => {
949 (Some(def), Some(self.tcx.fn_sig(def).output()))
954 let exp_is_struct = match exp_found.expected.sty {
955 TyKind::Adt(def, _) => def.is_struct(),
959 if let (Some(def_id), Some(ret_ty)) = (def_id, ret_ty) {
960 if exp_is_struct && &exp_found.expected == ret_ty.skip_binder() {
961 let message = format!(
962 "did you mean `{}(/* fields */)`?",
963 self.tcx.item_path_str(def_id)
965 diag.span_label(span, message);
970 diag.note_expected_found(&"type", expected, found);
976 self.check_and_note_conflicting_crates(diag, terr, span);
977 self.tcx.note_and_explain_type_err(diag, terr, span);
979 // It reads better to have the error origin as the final
981 self.note_error_origin(diag, &cause);
984 pub fn report_and_explain_type_error(
986 trace: TypeTrace<'tcx>,
987 terr: &TypeError<'tcx>,
988 ) -> DiagnosticBuilder<'tcx> {
990 "report_and_explain_type_error(trace={:?}, terr={:?})",
994 let span = trace.cause.span(&self.tcx);
995 let failure_code = trace.cause.as_failure_code(terr);
996 let mut diag = match failure_code {
997 FailureCode::Error0317(failure_str) => {
998 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1000 FailureCode::Error0580(failure_str) => {
1001 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1003 FailureCode::Error0308(failure_str) => {
1004 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1006 FailureCode::Error0644(failure_str) => {
1007 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1010 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1016 values: &ValuePairs<'tcx>,
1017 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1019 infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1020 infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1021 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1022 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1026 fn expected_found_str_ty(
1028 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1029 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1030 let exp_found = self.resolve_type_vars_if_possible(exp_found);
1031 if exp_found.references_error() {
1035 Some(self.cmp(exp_found.expected, exp_found.found))
1038 /// Returns a string of the form "expected `{}`, found `{}`".
1039 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1041 exp_found: &ty::error::ExpectedFound<T>,
1042 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1043 let exp_found = self.resolve_type_vars_if_possible(exp_found);
1044 if exp_found.references_error() {
1049 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1050 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1054 pub fn report_generic_bound_failure(
1056 region_scope_tree: ®ion::ScopeTree,
1058 origin: Option<SubregionOrigin<'tcx>>,
1059 bound_kind: GenericKind<'tcx>,
1062 self.construct_generic_bound_failure(region_scope_tree, span, origin, bound_kind, sub)
1066 pub fn construct_generic_bound_failure(
1068 region_scope_tree: ®ion::ScopeTree,
1070 origin: Option<SubregionOrigin<'tcx>>,
1071 bound_kind: GenericKind<'tcx>,
1073 ) -> DiagnosticBuilder<'a> {
1074 // Attempt to obtain the span of the parameter so we can
1075 // suggest adding an explicit lifetime bound to it.
1076 let type_param_span = match (self.in_progress_tables, bound_kind) {
1077 (Some(ref table), GenericKind::Param(ref param)) => {
1078 let table = table.borrow();
1079 table.local_id_root.and_then(|did| {
1080 let generics = self.tcx.generics_of(did);
1081 // Account for the case where `did` corresponds to `Self`, which doesn't have
1082 // the expected type argument.
1083 if !param.is_self() {
1084 let type_param = generics.type_param(param, self.tcx);
1085 let hir = &self.tcx.hir;
1086 hir.as_local_node_id(type_param.def_id).map(|id| {
1087 // Get the `hir::Param` to verify whether it already has any bounds.
1088 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1089 // instead we suggest `T: 'a + 'b` in that case.
1090 let mut has_bounds = false;
1091 if let Node::GenericParam(ref param) = hir.get(id) {
1092 has_bounds = !param.bounds.is_empty();
1094 let sp = hir.span(id);
1095 // `sp` only covers `T`, change it so that it covers
1096 // `T:` when appropriate
1097 let sp = if has_bounds {
1101 .next_point(self.tcx.sess.source_map().next_point(sp)))
1115 let labeled_user_string = match bound_kind {
1116 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1117 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1120 if let Some(SubregionOrigin::CompareImplMethodObligation {
1127 return self.report_extra_impl_obligation(
1132 &format!("`{}: {}`", bound_kind, sub),
1136 fn binding_suggestion<'tcx, S: fmt::Display>(
1137 err: &mut DiagnosticBuilder<'tcx>,
1138 type_param_span: Option<(Span, bool)>,
1139 bound_kind: GenericKind<'tcx>,
1142 let consider = &format!(
1143 "consider adding an explicit lifetime bound `{}: {}`...",
1146 if let Some((sp, has_lifetimes)) = type_param_span {
1147 let tail = if has_lifetimes { " + " } else { "" };
1148 let suggestion = format!("{}: {}{}", bound_kind, sub, tail);
1149 err.span_suggestion_short_with_applicability(
1153 Applicability::MaybeIncorrect, // Issue #41966
1160 let mut err = match *sub {
1162 | ty::ReFree(ty::FreeRegion {
1163 bound_region: ty::BrNamed(..),
1166 // Does the required lifetime have a nice name we can print?
1167 let mut err = struct_span_err!(
1171 "{} may not live long enough",
1174 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1179 // Does the required lifetime have a nice name we can print?
1180 let mut err = struct_span_err!(
1184 "{} may not live long enough",
1187 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1192 // If not, be less specific.
1193 let mut err = struct_span_err!(
1197 "{} may not live long enough",
1201 "consider adding an explicit lifetime bound for `{}`",
1204 self.tcx.note_and_explain_region(
1207 &format!("{} must be valid for ", labeled_user_string),
1215 if let Some(origin) = origin {
1216 self.note_region_origin(&mut err, &origin);
1221 fn report_sub_sup_conflict(
1223 region_scope_tree: ®ion::ScopeTree,
1224 var_origin: RegionVariableOrigin,
1225 sub_origin: SubregionOrigin<'tcx>,
1226 sub_region: Region<'tcx>,
1227 sup_origin: SubregionOrigin<'tcx>,
1228 sup_region: Region<'tcx>,
1230 let mut err = self.report_inference_failure(var_origin);
1232 self.tcx.note_and_explain_region(
1235 "first, the lifetime cannot outlive ",
1240 match (&sup_origin, &sub_origin) {
1241 (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1242 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1243 self.values_str(&sup_trace.values),
1244 self.values_str(&sub_trace.values),
1246 if sub_expected == sup_expected && sub_found == sup_found {
1247 self.tcx.note_and_explain_region(
1250 "...but the lifetime must also be valid for ",
1255 "...so that the {}:\nexpected {}\n found {}",
1256 sup_trace.cause.as_requirement_str(),
1257 sup_expected.content(),
1268 self.note_region_origin(&mut err, &sup_origin);
1270 self.tcx.note_and_explain_region(
1273 "but, the lifetime must be valid for ",
1278 self.note_region_origin(&mut err, &sub_origin);
1283 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1284 fn report_inference_failure(
1286 var_origin: RegionVariableOrigin,
1287 ) -> DiagnosticBuilder<'tcx> {
1288 let br_string = |br: ty::BoundRegion| {
1289 let mut s = br.to_string();
1295 let var_description = match var_origin {
1296 infer::MiscVariable(_) => String::new(),
1297 infer::PatternRegion(_) => " for pattern".to_string(),
1298 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1299 infer::Autoref(_) => " for autoref".to_string(),
1300 infer::Coercion(_) => " for automatic coercion".to_string(),
1301 infer::LateBoundRegion(_, br, infer::FnCall) => {
1302 format!(" for lifetime parameter {}in function call", br_string(br))
1304 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1305 format!(" for lifetime parameter {}in generic type", br_string(br))
1307 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1308 " for lifetime parameter {}in trait containing associated type `{}`",
1310 self.tcx.associated_item(def_id).ident
1312 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1313 infer::BoundRegionInCoherence(name) => {
1314 format!(" for lifetime parameter `{}` in coherence check", name)
1316 infer::UpvarRegion(ref upvar_id, _) => {
1317 let var_node_id = self.tcx.hir.hir_to_node_id(upvar_id.var_id);
1318 let var_name = self.tcx.hir.name(var_node_id);
1319 format!(" for capture of `{}` by closure", var_name)
1321 infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1328 "cannot infer an appropriate lifetime{} \
1329 due to conflicting requirements",
1336 Error0317(&'static str),
1337 Error0580(&'static str),
1338 Error0308(&'static str),
1339 Error0644(&'static str),
1342 impl<'tcx> ObligationCause<'tcx> {
1343 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1344 use self::FailureCode::*;
1345 use traits::ObligationCauseCode::*;
1347 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1348 MatchExpressionArm { source, .. } => Error0308(match source {
1349 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have incompatible types",
1350 hir::MatchSource::TryDesugar => {
1351 "try expression alternatives have incompatible types"
1353 _ => "match arms have incompatible types",
1355 IfExpression => Error0308("if and else have incompatible types"),
1356 IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1357 MainFunctionType => Error0580("main function has wrong type"),
1358 StartFunctionType => Error0308("start function has wrong type"),
1359 IntrinsicType => Error0308("intrinsic has wrong type"),
1360 MethodReceiver => Error0308("mismatched method receiver"),
1362 // In the case where we have no more specific thing to
1363 // say, also take a look at the error code, maybe we can
1366 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1367 Error0644("closure/generator type that references itself")
1369 _ => Error0308("mismatched types"),
1374 fn as_requirement_str(&self) -> &'static str {
1375 use traits::ObligationCauseCode::*;
1377 CompareImplMethodObligation { .. } => "method type is compatible with trait",
1378 ExprAssignable => "expression is assignable",
1379 MatchExpressionArm { source, .. } => match source {
1380 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1381 _ => "match arms have compatible types",
1383 IfExpression => "if and else have compatible types",
1384 IfExpressionWithNoElse => "if missing an else returns ()",
1385 MainFunctionType => "`main` function has the correct type",
1386 StartFunctionType => "`start` function has the correct type",
1387 IntrinsicType => "intrinsic has the correct type",
1388 MethodReceiver => "method receiver has the correct type",
1389 _ => "types are compatible",