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 ty::ReEmpty => ("an empty lifetime".to_owned(), None),
182 _ => bug!("{:?}", region),
186 fn msg_span_from_early_bound_and_free_regions(
188 region: ty::Region<'tcx>,
189 ) -> (String, Option<Span>) {
190 let cm = self.sess.source_map();
192 let scope = region.free_region_binding_scope(self);
193 let node = self.hir().as_local_node_id(scope).unwrap_or(DUMMY_NODE_ID);
194 let tag = match self.hir().find(node) {
195 Some(Node::Block(_)) | Some(Node::Expr(_)) => "body",
196 Some(Node::Item(it)) => Self::item_scope_tag(&it),
197 Some(Node::TraitItem(it)) => Self::trait_item_scope_tag(&it),
198 Some(Node::ImplItem(it)) => Self::impl_item_scope_tag(&it),
201 let (prefix, span) = match *region {
202 ty::ReEarlyBound(ref br) => {
203 let mut sp = cm.def_span(self.hir().span(node));
204 if let Some(param) = self.hir()
206 .and_then(|generics| generics.get_named(&br.name))
210 (format!("the lifetime {} as defined on", br.name), sp)
212 ty::ReFree(ty::FreeRegion {
213 bound_region: ty::BoundRegion::BrNamed(_, ref name),
216 let mut sp = cm.def_span(self.hir().span(node));
217 if let Some(param) = self.hir()
219 .and_then(|generics| generics.get_named(&name))
223 (format!("the lifetime {} as defined on", name), sp)
225 ty::ReFree(ref fr) => match fr.bound_region {
227 format!("the anonymous lifetime #{} defined on", idx + 1),
228 self.hir().span(node),
231 "an anonymous lifetime defined on".to_owned(),
232 self.hir().span(node),
235 format!("the lifetime {} as defined on", fr.bound_region),
236 cm.def_span(self.hir().span(node)),
241 let (msg, opt_span) = self.explain_span(tag, span);
242 (format!("{} {}", prefix, msg), opt_span)
246 err: &mut DiagnosticBuilder<'_>,
252 let message = format!("{}{}{}", prefix, description, suffix);
254 if let Some(span) = span {
255 err.span_note(span, &message);
261 fn item_scope_tag(item: &hir::Item) -> &'static str {
263 hir::ItemKind::Impl(..) => "impl",
264 hir::ItemKind::Struct(..) => "struct",
265 hir::ItemKind::Union(..) => "union",
266 hir::ItemKind::Enum(..) => "enum",
267 hir::ItemKind::Trait(..) => "trait",
268 hir::ItemKind::Fn(..) => "function body",
273 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
275 hir::TraitItemKind::Method(..) => "method body",
276 hir::TraitItemKind::Const(..) | hir::TraitItemKind::Type(..) => "associated item",
280 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
282 hir::ImplItemKind::Method(..) => "method body",
283 hir::ImplItemKind::Const(..)
284 | hir::ImplItemKind::Existential(..)
285 | hir::ImplItemKind::Type(..) => "associated item",
289 fn explain_span(self, heading: &str, span: Span) -> (String, Option<Span>) {
290 let lo = self.sess.source_map().lookup_char_pos_adj(span.lo());
292 format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize() + 1),
298 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
299 pub fn report_region_errors(
301 region_scope_tree: ®ion::ScopeTree,
302 errors: &Vec<RegionResolutionError<'tcx>>,
303 suppress: SuppressRegionErrors,
306 "report_region_errors(): {} errors to start, suppress = {:?}",
311 if suppress.suppressed() {
315 // try to pre-process the errors, which will group some of them
316 // together into a `ProcessedErrors` group:
317 let errors = self.process_errors(errors);
320 "report_region_errors: {} errors after preprocessing",
324 for error in errors {
325 debug!("report_region_errors: error = {:?}", error);
327 if !self.try_report_nice_region_error(&error) {
328 match error.clone() {
329 // These errors could indicate all manner of different
330 // problems with many different solutions. Rather
331 // than generate a "one size fits all" error, what we
332 // attempt to do is go through a number of specific
333 // scenarios and try to find the best way to present
334 // the error. If all of these fails, we fall back to a rather
335 // general bit of code that displays the error information
336 RegionResolutionError::ConcreteFailure(origin, sub, sup) => {
337 self.report_concrete_failure(region_scope_tree, origin, sub, sup)
341 RegionResolutionError::GenericBoundFailure(origin, param_ty, sub) => {
342 self.report_generic_bound_failure(
351 RegionResolutionError::SubSupConflict(
358 self.report_sub_sup_conflict(
372 // This method goes through all the errors and try to group certain types
373 // of error together, for the purpose of suggesting explicit lifetime
374 // parameters to the user. This is done so that we can have a more
375 // complete view of what lifetimes should be the same.
376 // If the return value is an empty vector, it means that processing
377 // failed (so the return value of this method should not be used).
379 // The method also attempts to weed out messages that seem like
380 // duplicates that will be unhelpful to the end-user. But
381 // obviously it never weeds out ALL errors.
384 errors: &Vec<RegionResolutionError<'tcx>>,
385 ) -> Vec<RegionResolutionError<'tcx>> {
386 debug!("process_errors()");
388 // We want to avoid reporting generic-bound failures if we can
389 // avoid it: these have a very high rate of being unhelpful in
390 // practice. This is because they are basically secondary
391 // checks that test the state of the region graph after the
392 // rest of inference is done, and the other kinds of errors
393 // indicate that the region constraint graph is internally
394 // inconsistent, so these test results are likely to be
397 // Therefore, we filter them out of the list unless they are
398 // the only thing in the list.
400 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
401 RegionResolutionError::GenericBoundFailure(..) => true,
402 RegionResolutionError::ConcreteFailure(..)
403 | RegionResolutionError::SubSupConflict(..) => false,
406 let mut errors = if errors.iter().all(|e| is_bound_failure(e)) {
411 .filter(|&e| !is_bound_failure(e))
416 // sort the errors by span, for better error message stability.
417 errors.sort_by_key(|u| match *u {
418 RegionResolutionError::ConcreteFailure(ref sro, _, _) => sro.span(),
419 RegionResolutionError::GenericBoundFailure(ref sro, _, _) => sro.span(),
420 RegionResolutionError::SubSupConflict(ref rvo, _, _, _, _) => rvo.span(),
425 /// Adds a note if the types come from similarly named crates
426 fn check_and_note_conflicting_crates(
428 err: &mut DiagnosticBuilder<'_>,
429 terr: &TypeError<'tcx>,
432 let report_path_match = |err: &mut DiagnosticBuilder<'_>, did1: DefId, did2: DefId| {
433 // Only external crates, if either is from a local
434 // module we could have false positives
435 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
436 let exp_path = self.tcx.item_path_str(did1);
437 let found_path = self.tcx.item_path_str(did2);
438 let exp_abs_path = self.tcx.absolute_item_path_str(did1);
439 let found_abs_path = self.tcx.absolute_item_path_str(did2);
440 // We compare strings because DefPath can be different
441 // for imported and non-imported crates
442 if exp_path == found_path || exp_abs_path == found_abs_path {
443 let crate_name = self.tcx.crate_name(did1.krate);
447 "Perhaps two different versions \
448 of crate `{}` are being used?",
456 TypeError::Sorts(ref exp_found) => {
457 // if they are both "path types", there's a chance of ambiguity
458 // due to different versions of the same crate
459 if let (&ty::Adt(exp_adt, _), &ty::Adt(found_adt, _))
460 = (&exp_found.expected.sty, &exp_found.found.sty)
462 report_path_match(err, exp_adt.did, found_adt.did);
465 TypeError::Traits(ref exp_found) => {
466 report_path_match(err, exp_found.expected, exp_found.found);
468 _ => (), // FIXME(#22750) handle traits and stuff
472 fn note_error_origin(&self, err: &mut DiagnosticBuilder<'tcx>, cause: &ObligationCause<'tcx>) {
474 ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
475 hir::MatchSource::IfLetDesugar { .. } => {
476 let msg = "`if let` arm with an incompatible type";
477 if self.tcx.sess.source_map().is_multiline(arm_span) {
478 err.span_note(arm_span, msg);
480 err.span_label(arm_span, msg);
483 hir::MatchSource::TryDesugar => {}
485 let msg = "match arm with an incompatible type";
486 if self.tcx.sess.source_map().is_multiline(arm_span) {
487 err.span_note(arm_span, msg);
489 err.span_label(arm_span, msg);
497 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
498 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
499 /// populate `other_value` with `other_ty`.
503 /// ^^^^--------^ this is highlighted
505 /// | this type argument is exactly the same as the other type, not highlighted
506 /// this is highlighted
508 /// -------- this type is the same as a type argument in the other type, not highlighted
512 value: &mut DiagnosticStyledString,
513 other_value: &mut DiagnosticStyledString,
515 sub: &ty::subst::Substs<'tcx>,
519 // `value` and `other_value` hold two incomplete type representation for display.
520 // `name` is the path of both types being compared. `sub`
521 value.push_highlighted(name);
524 value.push_highlighted("<");
527 // Output the lifetimes for the first type
528 let lifetimes = sub.regions()
530 let s = lifetime.to_string();
539 if !lifetimes.is_empty() {
540 if sub.regions().count() < len {
541 value.push_normal(lifetimes + &", ");
543 value.push_normal(lifetimes);
547 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
548 // `pos` and `other_ty`.
549 for (i, type_arg) in sub.types().enumerate() {
551 let values = self.cmp(type_arg, other_ty);
552 value.0.extend((values.0).0);
553 other_value.0.extend((values.1).0);
555 value.push_highlighted(type_arg.to_string());
558 if len > 0 && i != len - 1 {
559 value.push_normal(", ");
561 //self.push_comma(&mut value, &mut other_value, len, i);
564 value.push_highlighted(">");
568 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
569 /// as that is the difference to the other type.
571 /// For the following code:
574 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
577 /// The type error output will behave in the following way:
581 /// ^^^^--------^ this is highlighted
583 /// | this type argument is exactly the same as the other type, not highlighted
584 /// this is highlighted
586 /// -------- this type is the same as a type argument in the other type, not highlighted
590 mut t1_out: &mut DiagnosticStyledString,
591 mut t2_out: &mut DiagnosticStyledString,
593 sub: &ty::subst::Substs<'tcx>,
597 for (i, ta) in sub.types().enumerate() {
599 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
602 if let &ty::Adt(def, _) = &ta.sty {
603 let path_ = self.tcx.item_path_str(def.did.clone());
604 if path_ == other_path {
605 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
613 /// Add a `,` to the type representation only if it is appropriate.
616 value: &mut DiagnosticStyledString,
617 other_value: &mut DiagnosticStyledString,
621 if len > 0 && pos != len - 1 {
622 value.push_normal(", ");
623 other_value.push_normal(", ");
627 /// For generic types with parameters with defaults, remove the parameters corresponding to
628 /// the defaults. This repeats a lot of the logic found in `PrintContext::parameterized`.
629 fn strip_generic_default_params(
632 substs: &ty::subst::Substs<'tcx>,
633 ) -> &'tcx ty::subst::Substs<'tcx> {
634 let generics = self.tcx.generics_of(def_id);
635 let mut num_supplied_defaults = 0;
636 let mut type_params = generics
640 .filter_map(|param| match param.kind {
641 ty::GenericParamDefKind::Lifetime => None,
642 ty::GenericParamDefKind::Type { has_default, .. } => {
643 Some((param.def_id, has_default))
648 let has_default = type_params.peek().map(|(_, has_default)| has_default);
649 *has_default.unwrap_or(&false)
652 let types = substs.types().rev();
653 for ((def_id, has_default), actual) in type_params.zip(types) {
657 if self.tcx.type_of(def_id).subst(self.tcx, substs) != actual {
660 num_supplied_defaults += 1;
663 let len = generics.params.len();
664 let mut generics = generics.clone();
665 generics.params.truncate(len - num_supplied_defaults);
666 substs.truncate_to(self.tcx, &generics)
669 /// Compare two given types, eliding parts that are the same between them and highlighting
670 /// relevant differences, and return two representation of those types for highlighted printing.
671 fn cmp(&self, t1: Ty<'tcx>, t2: Ty<'tcx>) -> (DiagnosticStyledString, DiagnosticStyledString) {
672 fn equals<'tcx>(a: &Ty<'tcx>, b: &Ty<'tcx>) -> bool {
673 match (&a.sty, &b.sty) {
674 (a, b) if *a == *b => true,
675 (&ty::Int(_), &ty::Infer(ty::InferTy::IntVar(_)))
676 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Int(_))
677 | (&ty::Infer(ty::InferTy::IntVar(_)), &ty::Infer(ty::InferTy::IntVar(_)))
678 | (&ty::Float(_), &ty::Infer(ty::InferTy::FloatVar(_)))
679 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Float(_))
680 | (&ty::Infer(ty::InferTy::FloatVar(_)), &ty::Infer(ty::InferTy::FloatVar(_))) => {
687 fn push_ty_ref<'tcx>(
688 r: &ty::Region<'tcx>,
690 mutbl: hir::Mutability,
691 s: &mut DiagnosticStyledString,
693 let r = &r.to_string();
694 s.push_highlighted(format!(
697 if r == "" { "" } else { " " },
698 if mutbl == hir::MutMutable { "mut " } else { "" }
700 s.push_normal(ty.to_string());
703 match (&t1.sty, &t2.sty) {
704 (&ty::Adt(def1, sub1), &ty::Adt(def2, sub2)) => {
705 let sub_no_defaults_1 = self.strip_generic_default_params(def1.did, sub1);
706 let sub_no_defaults_2 = self.strip_generic_default_params(def2.did, sub2);
707 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
708 let path1 = self.tcx.item_path_str(def1.did.clone());
709 let path2 = self.tcx.item_path_str(def2.did.clone());
710 if def1.did == def2.did {
711 // Easy case. Replace same types with `_` to shorten the output and highlight
712 // the differing ones.
713 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
716 // --- ^ type argument elided
718 // highlighted in output
719 values.0.push_normal(path1);
720 values.1.push_normal(path2);
722 // Avoid printing out default generic parameters that are common to both
724 let len1 = sub_no_defaults_1.len();
725 let len2 = sub_no_defaults_2.len();
726 let common_len = cmp::min(len1, len2);
727 let remainder1: Vec<_> = sub1.types().skip(common_len).collect();
728 let remainder2: Vec<_> = sub2.types().skip(common_len).collect();
729 let common_default_params = remainder1
732 .zip(remainder2.iter().rev())
733 .filter(|(a, b)| a == b)
735 let len = sub1.len() - common_default_params;
737 // Only draw `<...>` if there're lifetime/type arguments.
739 values.0.push_normal("<");
740 values.1.push_normal("<");
743 fn lifetime_display(lifetime: Region<'_>) -> String {
744 let s = lifetime.to_string();
751 // At one point we'd like to elide all lifetimes here, they are irrelevant for
752 // all diagnostics that use this output
756 // ^^ ^^ --- type arguments are not elided
758 // | elided as they were the same
759 // not elided, they were different, but irrelevant
760 let lifetimes = sub1.regions().zip(sub2.regions());
761 for (i, lifetimes) in lifetimes.enumerate() {
762 let l1 = lifetime_display(lifetimes.0);
763 let l2 = lifetime_display(lifetimes.1);
765 values.0.push_normal("'_");
766 values.1.push_normal("'_");
768 values.0.push_highlighted(l1);
769 values.1.push_highlighted(l2);
771 self.push_comma(&mut values.0, &mut values.1, len, i);
774 // We're comparing two types with the same path, so we compare the type
775 // arguments for both. If they are the same, do not highlight and elide from the
779 // ^ elided type as this type argument was the same in both sides
780 let type_arguments = sub1.types().zip(sub2.types());
781 let regions_len = sub1.regions().count();
782 for (i, (ta1, ta2)) in type_arguments.take(len).enumerate() {
783 let i = i + regions_len;
785 values.0.push_normal("_");
786 values.1.push_normal("_");
788 let (x1, x2) = self.cmp(ta1, ta2);
789 (values.0).0.extend(x1.0);
790 (values.1).0.extend(x2.0);
792 self.push_comma(&mut values.0, &mut values.1, len, i);
795 // Close the type argument bracket.
796 // Only draw `<...>` if there're lifetime/type arguments.
798 values.0.push_normal(">");
799 values.1.push_normal(">");
804 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
806 // ------- this type argument is exactly the same as the other type
808 if self.cmp_type_arg(
820 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
823 // ------- this type argument is exactly the same as the other type
824 if self.cmp_type_arg(
836 // We couldn't find anything in common, highlight everything.
837 // let x: Bar<Qux> = y::<Foo<Zar>>();
839 DiagnosticStyledString::highlighted(t1.to_string()),
840 DiagnosticStyledString::highlighted(t2.to_string()),
845 // When finding T != &T, highlight only the borrow
846 (&ty::Ref(r1, ref_ty1, mutbl1), _) if equals(&ref_ty1, &t2) => {
847 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
848 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
849 values.1.push_normal(t2.to_string());
852 (_, &ty::Ref(r2, ref_ty2, mutbl2)) if equals(&t1, &ref_ty2) => {
853 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
854 values.0.push_normal(t1.to_string());
855 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
859 // When encountering &T != &mut T, highlight only the borrow
860 (&ty::Ref(r1, ref_ty1, mutbl1), &ty::Ref(r2, ref_ty2, mutbl2))
861 if equals(&ref_ty1, &ref_ty2) =>
863 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
864 push_ty_ref(&r1, ref_ty1, mutbl1, &mut values.0);
865 push_ty_ref(&r2, ref_ty2, mutbl2, &mut values.1);
871 // The two types are the same, elide and don't highlight.
873 DiagnosticStyledString::normal("_"),
874 DiagnosticStyledString::normal("_"),
877 // We couldn't find anything in common, highlight everything.
879 DiagnosticStyledString::highlighted(t1.to_string()),
880 DiagnosticStyledString::highlighted(t2.to_string()),
887 pub fn note_type_err(
889 diag: &mut DiagnosticBuilder<'tcx>,
890 cause: &ObligationCause<'tcx>,
891 secondary_span: Option<(Span, String)>,
892 mut values: Option<ValuePairs<'tcx>>,
893 terr: &TypeError<'tcx>,
895 // For some types of errors, expected-found does not make
896 // sense, so just ignore the values we were given.
898 TypeError::CyclicTy(_) => {
904 let (expected_found, exp_found, is_simple_error) = match values {
905 None => (None, None, false),
907 let (is_simple_error, exp_found) = match values {
908 ValuePairs::Types(exp_found) => {
910 exp_found.expected.is_primitive() && exp_found.found.is_primitive();
912 (is_simple_err, Some(exp_found))
916 let vals = match self.values_str(&values) {
917 Some((expected, found)) => Some((expected, found)),
919 // Derived error. Cancel the emitter.
920 self.tcx.sess.diagnostic().cancel(diag);
924 (vals, exp_found, is_simple_error)
928 let span = cause.span(&self.tcx);
930 diag.span_label(span, terr.to_string());
931 if let Some((sp, msg)) = secondary_span {
932 diag.span_label(sp, msg);
935 if let Some((expected, found)) = expected_found {
936 match (terr, is_simple_error, expected == found) {
937 (&TypeError::Sorts(ref values), false, true) => {
938 diag.note_expected_found_extra(
942 &format!(" ({})", values.expected.sort_string(self.tcx)),
943 &format!(" ({})", values.found.sort_string(self.tcx)),
947 if let Some(exp_found) = exp_found {
948 let (def_id, ret_ty) = match exp_found.found.sty {
949 TyKind::FnDef(def, _) => {
950 (Some(def), Some(self.tcx.fn_sig(def).output()))
955 let exp_is_struct = match exp_found.expected.sty {
956 TyKind::Adt(def, _) => def.is_struct(),
960 if let (Some(def_id), Some(ret_ty)) = (def_id, ret_ty) {
961 if exp_is_struct && &exp_found.expected == ret_ty.skip_binder() {
962 let message = format!(
963 "did you mean `{}(/* fields */)`?",
964 self.tcx.item_path_str(def_id)
966 diag.span_label(span, message);
971 diag.note_expected_found(&"type", expected, found);
977 self.check_and_note_conflicting_crates(diag, terr, span);
978 self.tcx.note_and_explain_type_err(diag, terr, span);
980 // It reads better to have the error origin as the final
982 self.note_error_origin(diag, &cause);
985 pub fn report_and_explain_type_error(
987 trace: TypeTrace<'tcx>,
988 terr: &TypeError<'tcx>,
989 ) -> DiagnosticBuilder<'tcx> {
991 "report_and_explain_type_error(trace={:?}, terr={:?})",
995 let span = trace.cause.span(&self.tcx);
996 let failure_code = trace.cause.as_failure_code(terr);
997 let mut diag = match failure_code {
998 FailureCode::Error0317(failure_str) => {
999 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
1001 FailureCode::Error0580(failure_str) => {
1002 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
1004 FailureCode::Error0308(failure_str) => {
1005 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
1007 FailureCode::Error0644(failure_str) => {
1008 struct_span_err!(self.tcx.sess, span, E0644, "{}", failure_str)
1011 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
1017 values: &ValuePairs<'tcx>,
1018 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1020 infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
1021 infer::Regions(ref exp_found) => self.expected_found_str(exp_found),
1022 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1023 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
1027 fn expected_found_str_ty(
1029 exp_found: &ty::error::ExpectedFound<Ty<'tcx>>,
1030 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1031 let exp_found = self.resolve_type_vars_if_possible(exp_found);
1032 if exp_found.references_error() {
1036 Some(self.cmp(exp_found.expected, exp_found.found))
1039 /// Returns a string of the form "expected `{}`, found `{}`".
1040 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
1042 exp_found: &ty::error::ExpectedFound<T>,
1043 ) -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
1044 let exp_found = self.resolve_type_vars_if_possible(exp_found);
1045 if exp_found.references_error() {
1050 DiagnosticStyledString::highlighted(exp_found.expected.to_string()),
1051 DiagnosticStyledString::highlighted(exp_found.found.to_string()),
1055 pub fn report_generic_bound_failure(
1057 region_scope_tree: ®ion::ScopeTree,
1059 origin: Option<SubregionOrigin<'tcx>>,
1060 bound_kind: GenericKind<'tcx>,
1063 self.construct_generic_bound_failure(region_scope_tree, span, origin, bound_kind, sub)
1067 pub fn construct_generic_bound_failure(
1069 region_scope_tree: ®ion::ScopeTree,
1071 origin: Option<SubregionOrigin<'tcx>>,
1072 bound_kind: GenericKind<'tcx>,
1074 ) -> DiagnosticBuilder<'a> {
1075 // Attempt to obtain the span of the parameter so we can
1076 // suggest adding an explicit lifetime bound to it.
1077 let type_param_span = match (self.in_progress_tables, bound_kind) {
1078 (Some(ref table), GenericKind::Param(ref param)) => {
1079 let table = table.borrow();
1080 table.local_id_root.and_then(|did| {
1081 let generics = self.tcx.generics_of(did);
1082 // Account for the case where `did` corresponds to `Self`, which doesn't have
1083 // the expected type argument.
1084 if !param.is_self() {
1085 let type_param = generics.type_param(param, self.tcx);
1086 let hir = &self.tcx.hir();
1087 hir.as_local_node_id(type_param.def_id).map(|id| {
1088 // Get the `hir::Param` to verify whether it already has any bounds.
1089 // We do this to avoid suggesting code that ends up as `T: 'a'b`,
1090 // instead we suggest `T: 'a + 'b` in that case.
1091 let mut has_bounds = false;
1092 if let Node::GenericParam(ref param) = hir.get(id) {
1093 has_bounds = !param.bounds.is_empty();
1095 let sp = hir.span(id);
1096 // `sp` only covers `T`, change it so that it covers
1097 // `T:` when appropriate
1098 let is_impl_trait = bound_kind.to_string().starts_with("impl ");
1099 let sp = if has_bounds && !is_impl_trait {
1103 .next_point(self.tcx.sess.source_map().next_point(sp)))
1107 (sp, has_bounds, is_impl_trait)
1117 let labeled_user_string = match bound_kind {
1118 GenericKind::Param(ref p) => format!("the parameter type `{}`", p),
1119 GenericKind::Projection(ref p) => format!("the associated type `{}`", p),
1122 if let Some(SubregionOrigin::CompareImplMethodObligation {
1129 return self.report_extra_impl_obligation(
1134 &format!("`{}: {}`", bound_kind, sub),
1138 fn binding_suggestion<'tcx, S: fmt::Display>(
1139 err: &mut DiagnosticBuilder<'tcx>,
1140 type_param_span: Option<(Span, bool, bool)>,
1141 bound_kind: GenericKind<'tcx>,
1144 let consider = format!(
1145 "consider adding an explicit lifetime bound {}",
1146 if type_param_span.map(|(_, _, is_impl_trait)| is_impl_trait).unwrap_or(false) {
1147 format!(" `{}` to `{}`...", sub, bound_kind)
1149 format!("`{}: {}`...", bound_kind, sub)
1152 if let Some((sp, has_lifetimes, is_impl_trait)) = type_param_span {
1153 let suggestion = if is_impl_trait {
1154 format!("{} + {}", bound_kind, sub)
1156 let tail = if has_lifetimes { " + " } else { "" };
1157 format!("{}: {}{}", bound_kind, sub, tail)
1159 err.span_suggestion_short_with_applicability(
1163 Applicability::MaybeIncorrect, // Issue #41966
1166 err.help(&consider);
1170 let mut err = match *sub {
1172 | ty::ReFree(ty::FreeRegion {
1173 bound_region: ty::BrNamed(..),
1176 // Does the required lifetime have a nice name we can print?
1177 let mut err = struct_span_err!(
1181 "{} may not live long enough",
1184 binding_suggestion(&mut err, type_param_span, bound_kind, sub);
1189 // Does the required lifetime have a nice name we can print?
1190 let mut err = struct_span_err!(
1194 "{} may not live long enough",
1197 binding_suggestion(&mut err, type_param_span, bound_kind, "'static");
1202 // If not, be less specific.
1203 let mut err = struct_span_err!(
1207 "{} may not live long enough",
1211 "consider adding an explicit lifetime bound for `{}`",
1214 self.tcx.note_and_explain_region(
1217 &format!("{} must be valid for ", labeled_user_string),
1225 if let Some(origin) = origin {
1226 self.note_region_origin(&mut err, &origin);
1231 fn report_sub_sup_conflict(
1233 region_scope_tree: ®ion::ScopeTree,
1234 var_origin: RegionVariableOrigin,
1235 sub_origin: SubregionOrigin<'tcx>,
1236 sub_region: Region<'tcx>,
1237 sup_origin: SubregionOrigin<'tcx>,
1238 sup_region: Region<'tcx>,
1240 let mut err = self.report_inference_failure(var_origin);
1242 self.tcx.note_and_explain_region(
1245 "first, the lifetime cannot outlive ",
1250 match (&sup_origin, &sub_origin) {
1251 (&infer::Subtype(ref sup_trace), &infer::Subtype(ref sub_trace)) => {
1252 if let (Some((sup_expected, sup_found)), Some((sub_expected, sub_found))) = (
1253 self.values_str(&sup_trace.values),
1254 self.values_str(&sub_trace.values),
1256 if sub_expected == sup_expected && sub_found == sup_found {
1257 self.tcx.note_and_explain_region(
1260 "...but the lifetime must also be valid for ",
1265 "...so that the {}:\nexpected {}\n found {}",
1266 sup_trace.cause.as_requirement_str(),
1267 sup_expected.content(),
1278 self.note_region_origin(&mut err, &sup_origin);
1280 self.tcx.note_and_explain_region(
1283 "but, the lifetime must be valid for ",
1288 self.note_region_origin(&mut err, &sub_origin);
1293 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1294 fn report_inference_failure(
1296 var_origin: RegionVariableOrigin,
1297 ) -> DiagnosticBuilder<'tcx> {
1298 let br_string = |br: ty::BoundRegion| {
1299 let mut s = br.to_string();
1305 let var_description = match var_origin {
1306 infer::MiscVariable(_) => String::new(),
1307 infer::PatternRegion(_) => " for pattern".to_string(),
1308 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1309 infer::Autoref(_) => " for autoref".to_string(),
1310 infer::Coercion(_) => " for automatic coercion".to_string(),
1311 infer::LateBoundRegion(_, br, infer::FnCall) => {
1312 format!(" for lifetime parameter {}in function call", br_string(br))
1314 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1315 format!(" for lifetime parameter {}in generic type", br_string(br))
1317 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(def_id)) => format!(
1318 " for lifetime parameter {}in trait containing associated type `{}`",
1320 self.tcx.associated_item(def_id).ident
1322 infer::EarlyBoundRegion(_, name) => format!(" for lifetime parameter `{}`", name),
1323 infer::BoundRegionInCoherence(name) => {
1324 format!(" for lifetime parameter `{}` in coherence check", name)
1326 infer::UpvarRegion(ref upvar_id, _) => {
1327 let var_node_id = self.tcx.hir().hir_to_node_id(upvar_id.var_path.hir_id);
1328 let var_name = self.tcx.hir().name(var_node_id);
1329 format!(" for capture of `{}` by closure", var_name)
1331 infer::NLL(..) => bug!("NLL variable found in lexical phase"),
1338 "cannot infer an appropriate lifetime{} \
1339 due to conflicting requirements",
1346 Error0317(&'static str),
1347 Error0580(&'static str),
1348 Error0308(&'static str),
1349 Error0644(&'static str),
1352 impl<'tcx> ObligationCause<'tcx> {
1353 fn as_failure_code(&self, terr: &TypeError<'tcx>) -> FailureCode {
1354 use self::FailureCode::*;
1355 use traits::ObligationCauseCode::*;
1357 CompareImplMethodObligation { .. } => Error0308("method not compatible with trait"),
1358 MatchExpressionArm { source, .. } => Error0308(match source {
1359 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have incompatible types",
1360 hir::MatchSource::TryDesugar => {
1361 "try expression alternatives have incompatible types"
1363 _ => "match arms have incompatible types",
1365 IfExpression => Error0308("if and else have incompatible types"),
1366 IfExpressionWithNoElse => Error0317("if may be missing an else clause"),
1367 MainFunctionType => Error0580("main function has wrong type"),
1368 StartFunctionType => Error0308("start function has wrong type"),
1369 IntrinsicType => Error0308("intrinsic has wrong type"),
1370 MethodReceiver => Error0308("mismatched method receiver"),
1372 // In the case where we have no more specific thing to
1373 // say, also take a look at the error code, maybe we can
1376 TypeError::CyclicTy(ty) if ty.is_closure() || ty.is_generator() => {
1377 Error0644("closure/generator type that references itself")
1379 _ => Error0308("mismatched types"),
1384 fn as_requirement_str(&self) -> &'static str {
1385 use traits::ObligationCauseCode::*;
1387 CompareImplMethodObligation { .. } => "method type is compatible with trait",
1388 ExprAssignable => "expression is assignable",
1389 MatchExpressionArm { source, .. } => match source {
1390 hir::MatchSource::IfLetDesugar { .. } => "`if let` arms have compatible types",
1391 _ => "match arms have compatible types",
1393 IfExpression => "if and else have compatible types",
1394 IfExpressionWithNoElse => "if missing an else returns ()",
1395 MainFunctionType => "`main` function has the correct type",
1396 StartFunctionType => "`start` function has the correct type",
1397 IntrinsicType => "intrinsic has the correct type",
1398 MethodReceiver => "method receiver has the correct type",
1399 _ => "types are compatible",