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 catalogue 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, TypeTrace, SubregionOrigin, RegionVariableOrigin, ValuePairs};
60 use super::region_inference::{RegionResolutionError, ConcreteFailure, SubSupConflict,
61 GenericBoundFailure, GenericKind};
65 use hir::map as hir_map;
66 use hir::def_id::DefId;
68 use traits::{ObligationCause, ObligationCauseCode};
69 use ty::{self, TyCtxt, TypeFoldable};
70 use ty::{Region, Issue32330};
71 use ty::error::TypeError;
72 use syntax_pos::{Pos, Span};
73 use errors::{DiagnosticBuilder, DiagnosticStyledString};
77 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
78 pub fn note_and_explain_region(self,
79 err: &mut DiagnosticBuilder,
81 region: &'tcx ty::Region,
83 fn item_scope_tag(item: &hir::Item) -> &'static str {
85 hir::ItemImpl(..) => "impl",
86 hir::ItemStruct(..) => "struct",
87 hir::ItemUnion(..) => "union",
88 hir::ItemEnum(..) => "enum",
89 hir::ItemTrait(..) => "trait",
90 hir::ItemFn(..) => "function body",
95 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
97 hir::TraitItemKind::Method(..) => "method body",
98 hir::TraitItemKind::Const(..) |
99 hir::TraitItemKind::Type(..) => "associated item"
103 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
105 hir::ImplItemKind::Method(..) => "method body",
106 hir::ImplItemKind::Const(..) |
107 hir::ImplItemKind::Type(_) => "associated item"
111 fn explain_span<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
112 heading: &str, span: Span)
113 -> (String, Option<Span>) {
114 let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
115 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
119 let (description, span) = match *region {
120 ty::ReScope(scope) => {
122 let unknown_scope = || {
123 format!("{}unknown scope: {:?}{}. Please report a bug.",
124 prefix, scope, suffix)
126 let span = match scope.span(&self.region_maps, &self.hir) {
129 err.note(&unknown_scope());
133 let tag = match self.hir.find(scope.node_id(&self.region_maps)) {
134 Some(hir_map::NodeBlock(_)) => "block",
135 Some(hir_map::NodeExpr(expr)) => match expr.node {
136 hir::ExprCall(..) => "call",
137 hir::ExprMethodCall(..) => "method call",
138 hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
139 hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) => "while let",
140 hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) => "for",
141 hir::ExprMatch(..) => "match",
144 Some(hir_map::NodeStmt(_)) => "statement",
145 Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
146 Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
147 Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
149 err.span_note(span, &unknown_scope());
153 let scope_decorated_tag = match self.region_maps.code_extent_data(scope) {
154 region::CodeExtentData::Misc(_) => tag,
155 region::CodeExtentData::CallSiteScope { .. } => {
156 "scope of call-site for function"
158 region::CodeExtentData::ParameterScope { .. } => {
159 "scope of function body"
161 region::CodeExtentData::DestructionScope(_) => {
162 new_string = format!("destruction scope surrounding {}", tag);
165 region::CodeExtentData::Remainder(r) => {
166 new_string = format!("block suffix following statement {}",
167 r.first_statement_index);
171 explain_span(self, scope_decorated_tag, span)
174 ty::ReFree(ref fr) => {
175 let prefix = match fr.bound_region {
177 format!("the anonymous lifetime #{} defined on", idx + 1)
179 ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
181 format!("the lifetime {} as defined on",
186 let node = fr.scope.node_id(&self.region_maps);
188 let tag = match self.hir.find(node) {
189 Some(hir_map::NodeBlock(_)) |
190 Some(hir_map::NodeExpr(_)) => "body",
191 Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
192 Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
193 Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
195 // this really should not happen, but it does:
198 unknown = format!("unexpected node ({}) for scope {:?}. \
199 Please report a bug.",
200 self.hir.node_to_string(node), fr.scope);
204 unknown = format!("unknown node for scope {:?}. \
205 Please report a bug.", fr.scope);
209 let (msg, opt_span) = explain_span(self, tag, self.hir.span(node));
210 (format!("{} {}", prefix, msg), opt_span)
213 ty::ReStatic => ("the static lifetime".to_owned(), None),
215 ty::ReEmpty => ("the empty lifetime".to_owned(), None),
217 ty::ReEarlyBound(ref data) => (data.name.to_string(), None),
219 // FIXME(#13998) ReSkolemized should probably print like
220 // ReFree rather than dumping Debug output on the user.
222 // We shouldn't really be having unification failures with ReVar
223 // and ReLateBound though.
224 ty::ReSkolemized(..) |
226 ty::ReLateBound(..) |
228 (format!("lifetime {:?}", region), None)
231 let message = format!("{}{}{}", prefix, description, suffix);
232 if let Some(span) = span {
233 err.span_note(span, &message);
240 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
241 pub fn report_region_errors(&self,
242 errors: &Vec<RegionResolutionError<'tcx>>) {
243 debug!("report_region_errors(): {} errors to start", errors.len());
245 // try to pre-process the errors, which will group some of them
246 // together into a `ProcessedErrors` group:
247 let errors = self.process_errors(errors);
249 debug!("report_region_errors: {} errors after preprocessing", errors.len());
251 for error in errors {
252 debug!("report_region_errors: error = {:?}", error);
253 match error.clone() {
254 ConcreteFailure(origin, sub, sup) => {
255 self.report_concrete_failure(origin, sub, sup).emit();
258 GenericBoundFailure(kind, param_ty, sub) => {
259 self.report_generic_bound_failure(kind, param_ty, sub);
262 SubSupConflict(var_origin,
264 sup_origin, sup_r) => {
265 self.report_sub_sup_conflict(var_origin,
273 // This method goes through all the errors and try to group certain types
274 // of error together, for the purpose of suggesting explicit lifetime
275 // parameters to the user. This is done so that we can have a more
276 // complete view of what lifetimes should be the same.
277 // If the return value is an empty vector, it means that processing
278 // failed (so the return value of this method should not be used).
280 // The method also attempts to weed out messages that seem like
281 // duplicates that will be unhelpful to the end-user. But
282 // obviously it never weeds out ALL errors.
283 fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
284 -> Vec<RegionResolutionError<'tcx>> {
285 debug!("process_errors()");
287 // We want to avoid reporting generic-bound failures if we can
288 // avoid it: these have a very high rate of being unhelpful in
289 // practice. This is because they are basically secondary
290 // checks that test the state of the region graph after the
291 // rest of inference is done, and the other kinds of errors
292 // indicate that the region constraint graph is internally
293 // inconsistent, so these test results are likely to be
296 // Therefore, we filter them out of the list unless they are
297 // the only thing in the list.
299 let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
300 ConcreteFailure(..) => false,
301 SubSupConflict(..) => false,
302 GenericBoundFailure(..) => true,
305 if errors.iter().all(|e| is_bound_failure(e)) {
308 errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
312 /// Adds a note if the types come from similarly named crates
313 fn check_and_note_conflicting_crates(&self,
314 err: &mut DiagnosticBuilder,
315 terr: &TypeError<'tcx>,
317 let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
318 // Only external crates, if either is from a local
319 // module we could have false positives
320 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
321 let exp_path = self.tcx.item_path_str(did1);
322 let found_path = self.tcx.item_path_str(did2);
323 // We compare strings because DefPath can be different
324 // for imported and non-imported crates
325 if exp_path == found_path {
326 let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
327 err.span_note(sp, &format!("Perhaps two different versions \
328 of crate `{}` are being used?",
334 TypeError::Sorts(ref exp_found) => {
335 // if they are both "path types", there's a chance of ambiguity
336 // due to different versions of the same crate
337 match (&exp_found.expected.sty, &exp_found.found.sty) {
338 (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
339 report_path_match(err, exp_adt.did, found_adt.did);
344 TypeError::Traits(ref exp_found) => {
345 report_path_match(err, exp_found.expected, exp_found.found);
347 _ => () // FIXME(#22750) handle traits and stuff
351 fn note_error_origin(&self,
352 err: &mut DiagnosticBuilder<'tcx>,
353 cause: &ObligationCause<'tcx>)
356 ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
357 hir::MatchSource::IfLetDesugar {..} => {
358 err.span_note(arm_span, "`if let` arm with an incompatible type");
361 err.span_note(arm_span, "match arm with an incompatible type");
368 /// Given that `other_ty` is the same as a type argument for `name` in `sub`, populate `value`
369 /// highlighting `name` and every type argument that isn't at `pos` (which is `other_ty`), and
370 /// populate `other_value` with `other_ty`.
374 /// ^^^^--------^ this is highlighted
376 /// | this type argument is exactly the same as the other type, not highlighted
377 /// this is highlighted
379 /// -------- this type is the same as a type argument in the other type, not highlighted
381 fn highlight_outer(&self,
382 mut value: &mut DiagnosticStyledString,
383 mut other_value: &mut DiagnosticStyledString,
385 sub: &ty::subst::Substs<'tcx>,
387 other_ty: &ty::Ty<'tcx>) {
388 // `value` and `other_value` hold two incomplete type representation for display.
389 // `name` is the path of both types being compared. `sub`
390 value.push_highlighted(name);
393 value.push_highlighted("<");
396 // Output the lifetimes fot the first type
397 let lifetimes = sub.regions().map(|lifetime| {
398 let s = format!("{}", lifetime);
404 }).collect::<Vec<_>>().join(", ");
405 if !lifetimes.is_empty() {
406 if sub.regions().count() < len {
407 value.push_normal(lifetimes + &", ");
409 value.push_normal(lifetimes);
413 // Highlight all the type arguments that aren't at `pos` and compare the type argument at
414 // `pos` and `other_ty`.
415 for (i, type_arg) in sub.types().enumerate() {
417 let values = self.cmp(type_arg, other_ty);
418 value.0.extend((values.0).0);
419 other_value.0.extend((values.1).0);
421 value.push_highlighted(format!("{}", type_arg));
424 if len > 0 && i != len - 1 {
425 value.push_normal(", ");
427 //self.push_comma(&mut value, &mut other_value, len, i);
430 value.push_highlighted(">");
434 /// If `other_ty` is the same as a type argument present in `sub`, highlight `path` in `t1_out`,
435 /// as that is the difference to the other type.
437 /// For the following code:
440 /// let x: Foo<Bar<Qux>> = foo::<Bar<Qux>>();
443 /// The type error output will behave in the following way:
447 /// ^^^^--------^ this is highlighted
449 /// | this type argument is exactly the same as the other type, not highlighted
450 /// this is highlighted
452 /// -------- this type is the same as a type argument in the other type, not highlighted
454 fn cmp_type_arg(&self,
455 mut t1_out: &mut DiagnosticStyledString,
456 mut t2_out: &mut DiagnosticStyledString,
458 sub: &ty::subst::Substs<'tcx>,
460 other_ty: &ty::Ty<'tcx>) -> Option<()> {
461 for (i, ta) in sub.types().enumerate() {
463 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
466 if let &ty::TyAdt(def, _) = &ta.sty {
467 let path_ = self.tcx.item_path_str(def.did.clone());
468 if path_ == other_path {
469 self.highlight_outer(&mut t1_out, &mut t2_out, path, sub, i, &other_ty);
477 /// Add a `,` to the type representation only if it is appropriate.
479 value: &mut DiagnosticStyledString,
480 other_value: &mut DiagnosticStyledString,
483 if len > 0 && pos != len - 1 {
484 value.push_normal(", ");
485 other_value.push_normal(", ");
489 /// Compare two given types, eliding parts that are the same between them and highlighting
490 /// relevant differences, and return two representation of those types for highlighted printing.
491 fn cmp(&self, t1: ty::Ty<'tcx>, t2: ty::Ty<'tcx>)
492 -> (DiagnosticStyledString, DiagnosticStyledString)
494 match (&t1.sty, &t2.sty) {
495 (&ty::TyAdt(def1, sub1), &ty::TyAdt(def2, sub2)) => {
496 let mut values = (DiagnosticStyledString::new(), DiagnosticStyledString::new());
497 let path1 = self.tcx.item_path_str(def1.did.clone());
498 let path2 = self.tcx.item_path_str(def2.did.clone());
499 if def1.did == def2.did {
500 // Easy case. Replace same types with `_` to shorten the output and highlight
501 // the differing ones.
502 // let x: Foo<Bar, Qux> = y::<Foo<Quz, Qux>>();
505 // --- ^ type argument elided
507 // highlighted in output
508 values.0.push_normal(path1);
509 values.1.push_normal(path2);
511 // Only draw `<...>` if there're lifetime/type arguments.
512 let len = sub1.len();
514 values.0.push_normal("<");
515 values.1.push_normal("<");
518 fn lifetime_display(lifetime: &Region) -> String {
519 let s = format!("{}", lifetime);
526 // At one point we'd like to elide all lifetimes here, they are irrelevant for
527 // all diagnostics that use this output
531 // ^^ ^^ --- type arguments are not elided
533 // | elided as they were the same
534 // not elided, they were different, but irrelevant
535 let lifetimes = sub1.regions().zip(sub2.regions());
536 for (i, lifetimes) in lifetimes.enumerate() {
537 let l1 = lifetime_display(lifetimes.0);
538 let l2 = lifetime_display(lifetimes.1);
540 values.0.push_normal("'_");
541 values.1.push_normal("'_");
543 values.0.push_highlighted(l1);
544 values.1.push_highlighted(l2);
546 self.push_comma(&mut values.0, &mut values.1, len, i);
549 // We're comparing two types with the same path, so we compare the type
550 // arguments for both. If they are the same, do not highlight and elide from the
554 // ^ elided type as this type argument was the same in both sides
555 let type_arguments = sub1.types().zip(sub2.types());
556 let regions_len = sub1.regions().collect::<Vec<_>>().len();
557 for (i, (ta1, ta2)) in type_arguments.enumerate() {
558 let i = i + regions_len;
560 values.0.push_normal("_");
561 values.1.push_normal("_");
563 let (x1, x2) = self.cmp(ta1, ta2);
564 (values.0).0.extend(x1.0);
565 (values.1).0.extend(x2.0);
567 self.push_comma(&mut values.0, &mut values.1, len, i);
570 // Close the type argument bracket.
571 // Only draw `<...>` if there're lifetime/type arguments.
573 values.0.push_normal(">");
574 values.1.push_normal(">");
579 // let x: Foo<Bar<Qux> = foo::<Bar<Qux>>();
581 // ------- this type argument is exactly the same as the other type
583 if self.cmp_type_arg(&mut values.0,
592 // let x: Bar<Qux> = y:<Foo<Bar<Qux>>>();
595 // ------- this type argument is exactly the same as the other type
596 if self.cmp_type_arg(&mut values.1,
605 // We couldn't find anything in common, highlight everything.
606 // let x: Bar<Qux> = y::<Foo<Zar>>();
607 (DiagnosticStyledString::highlighted(format!("{}", t1)),
608 DiagnosticStyledString::highlighted(format!("{}", t2)))
613 // The two types are the same, elide and don't highlight.
614 (DiagnosticStyledString::normal("_"), DiagnosticStyledString::normal("_"))
616 // We couldn't find anything in common, highlight everything.
617 (DiagnosticStyledString::highlighted(format!("{}", t1)),
618 DiagnosticStyledString::highlighted(format!("{}", t2)))
624 pub fn note_type_err(&self,
625 diag: &mut DiagnosticBuilder<'tcx>,
626 cause: &ObligationCause<'tcx>,
627 secondary_span: Option<(Span, String)>,
628 values: Option<ValuePairs<'tcx>>,
629 terr: &TypeError<'tcx>)
631 let (expected_found, is_simple_error) = match values {
632 None => (None, false),
634 let is_simple_error = match values {
635 ValuePairs::Types(exp_found) => {
636 exp_found.expected.is_primitive() && exp_found.found.is_primitive()
640 let vals = match self.values_str(&values) {
641 Some((expected, found)) => Some((expected, found)),
643 // Derived error. Cancel the emitter.
644 self.tcx.sess.diagnostic().cancel(diag);
648 (vals, is_simple_error)
652 let span = cause.span;
654 if let Some((expected, found)) = expected_found {
655 match (terr, is_simple_error, expected == found) {
656 (&TypeError::Sorts(ref values), false, true) => {
657 diag.note_expected_found_extra(
658 &"type", expected, found,
659 &format!(" ({})", values.expected.sort_string(self.tcx)),
660 &format!(" ({})", values.found.sort_string(self.tcx)));
663 diag.note_expected_found(&"type", expected, found);
669 diag.span_label(span, &terr);
670 if let Some((sp, msg)) = secondary_span {
671 diag.span_label(sp, &msg);
674 self.note_error_origin(diag, &cause);
675 self.check_and_note_conflicting_crates(diag, terr, span);
676 self.tcx.note_and_explain_type_err(diag, terr, span);
679 pub fn note_issue_32330(&self,
680 diag: &mut DiagnosticBuilder<'tcx>,
681 terr: &TypeError<'tcx>)
683 debug!("note_issue_32330: terr={:?}", terr);
685 TypeError::RegionsInsufficientlyPolymorphic(_, _, Some(box Issue32330 {
686 fn_def_id, region_name
688 TypeError::RegionsOverlyPolymorphic(_, _, Some(box Issue32330 {
689 fn_def_id, region_name
692 &format!("lifetime parameter `{0}` declared on fn `{1}` \
693 appears only in the return type, \
694 but here is required to be higher-ranked, \
695 which means that `{0}` must appear in both \
696 argument and return types",
698 self.tcx.item_path_str(fn_def_id)));
700 &format!("this error is the result of a recent bug fix; \
701 for more information, see issue #33685 \
702 <https://github.com/rust-lang/rust/issues/33685>"));
708 pub fn report_and_explain_type_error(&self,
709 trace: TypeTrace<'tcx>,
710 terr: &TypeError<'tcx>)
711 -> DiagnosticBuilder<'tcx>
713 let span = trace.cause.span;
714 let failure_str = trace.cause.as_failure_str();
715 let mut diag = match trace.cause.code {
716 ObligationCauseCode::IfExpressionWithNoElse => {
717 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
719 ObligationCauseCode::MainFunctionType => {
720 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
723 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
726 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
727 self.note_issue_32330(&mut diag, terr);
731 fn values_str(&self, values: &ValuePairs<'tcx>)
732 -> Option<(DiagnosticStyledString, DiagnosticStyledString)>
735 infer::Types(ref exp_found) => self.expected_found_str_ty(exp_found),
736 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
737 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
741 fn expected_found_str_ty(&self,
742 exp_found: &ty::error::ExpectedFound<ty::Ty<'tcx>>)
743 -> Option<(DiagnosticStyledString, DiagnosticStyledString)> {
744 let exp_found = self.resolve_type_vars_if_possible(exp_found);
745 if exp_found.references_error() {
749 Some(self.cmp(exp_found.expected, exp_found.found))
752 /// Returns a string of the form "expected `{}`, found `{}`".
753 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
755 exp_found: &ty::error::ExpectedFound<T>)
756 -> Option<(DiagnosticStyledString, DiagnosticStyledString)>
758 let exp_found = self.resolve_type_vars_if_possible(exp_found);
759 if exp_found.references_error() {
763 Some((DiagnosticStyledString::highlighted(format!("{}", exp_found.expected)),
764 DiagnosticStyledString::highlighted(format!("{}", exp_found.found))))
767 fn report_generic_bound_failure(&self,
768 origin: SubregionOrigin<'tcx>,
769 bound_kind: GenericKind<'tcx>,
772 // FIXME: it would be better to report the first error message
773 // with the span of the parameter itself, rather than the span
774 // where the error was detected. But that span is not readily
777 let labeled_user_string = match bound_kind {
778 GenericKind::Param(ref p) =>
779 format!("the parameter type `{}`", p),
780 GenericKind::Projection(ref p) =>
781 format!("the associated type `{}`", p),
784 if let SubregionOrigin::CompareImplMethodObligation {
785 span, item_name, impl_item_def_id, trait_item_def_id, lint_id
787 self.report_extra_impl_obligation(span,
791 &format!("`{}: {}`", bound_kind, sub),
797 let mut err = match *sub {
798 ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
799 // Does the required lifetime have a nice name we can print?
800 let mut err = struct_span_err!(self.tcx.sess,
803 "{} may not live long enough",
804 labeled_user_string);
805 err.help(&format!("consider adding an explicit lifetime bound `{}: {}`...",
812 // Does the required lifetime have a nice name we can print?
813 let mut err = struct_span_err!(self.tcx.sess,
816 "{} may not live long enough",
817 labeled_user_string);
818 err.help(&format!("consider adding an explicit lifetime \
819 bound `{}: 'static`...",
825 // If not, be less specific.
826 let mut err = struct_span_err!(self.tcx.sess,
829 "{} may not live long enough",
830 labeled_user_string);
831 err.help(&format!("consider adding an explicit lifetime bound for `{}`",
833 self.tcx.note_and_explain_region(
835 &format!("{} must be valid for ", labeled_user_string),
842 self.note_region_origin(&mut err, &origin);
846 fn report_sub_sup_conflict(&self,
847 var_origin: RegionVariableOrigin,
848 sub_origin: SubregionOrigin<'tcx>,
849 sub_region: &'tcx Region,
850 sup_origin: SubregionOrigin<'tcx>,
851 sup_region: &'tcx Region) {
852 let mut err = self.report_inference_failure(var_origin);
854 self.tcx.note_and_explain_region(&mut err,
855 "first, the lifetime cannot outlive ",
859 self.note_region_origin(&mut err, &sup_origin);
861 self.tcx.note_and_explain_region(&mut err,
862 "but, the lifetime must be valid for ",
866 self.note_region_origin(&mut err, &sub_origin);
871 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
872 fn report_inference_failure(&self,
873 var_origin: RegionVariableOrigin)
874 -> DiagnosticBuilder<'tcx> {
875 let br_string = |br: ty::BoundRegion| {
876 let mut s = br.to_string();
882 let var_description = match var_origin {
883 infer::MiscVariable(_) => "".to_string(),
884 infer::PatternRegion(_) => " for pattern".to_string(),
885 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
886 infer::Autoref(_) => " for autoref".to_string(),
887 infer::Coercion(_) => " for automatic coercion".to_string(),
888 infer::LateBoundRegion(_, br, infer::FnCall) => {
889 format!(" for lifetime parameter {}in function call",
892 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
893 format!(" for lifetime parameter {}in generic type", br_string(br))
895 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
896 format!(" for lifetime parameter {}in trait containing associated type `{}`",
897 br_string(br), type_name)
899 infer::EarlyBoundRegion(_, name, _) => {
900 format!(" for lifetime parameter `{}`",
903 infer::BoundRegionInCoherence(name) => {
904 format!(" for lifetime parameter `{}` in coherence check",
907 infer::UpvarRegion(ref upvar_id, _) => {
908 format!(" for capture of `{}` by closure",
909 self.tcx.local_var_name_str(upvar_id.var_id).to_string())
913 struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
914 "cannot infer an appropriate lifetime{} \
915 due to conflicting requirements",
920 impl<'tcx> ObligationCause<'tcx> {
921 fn as_failure_str(&self) -> &'static str {
922 use traits::ObligationCauseCode::*;
924 CompareImplMethodObligation { .. } => "method not compatible with trait",
925 MatchExpressionArm { source, .. } => match source {
926 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
927 _ => "match arms have incompatible types",
929 IfExpression => "if and else have incompatible types",
930 IfExpressionWithNoElse => "if may be missing an else clause",
931 EquatePredicate => "equality predicate not satisfied",
932 MainFunctionType => "main function has wrong type",
933 StartFunctionType => "start function has wrong type",
934 IntrinsicType => "intrinsic has wrong type",
935 MethodReceiver => "mismatched method receiver",
936 _ => "mismatched types",
940 fn as_requirement_str(&self) -> &'static str {
941 use traits::ObligationCauseCode::*;
943 CompareImplMethodObligation { .. } => "method type is compatible with trait",
944 ExprAssignable => "expression is assignable",
945 MatchExpressionArm { source, .. } => match source {
946 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have compatible types",
947 _ => "match arms have compatible types",
949 IfExpression => "if and else have compatible types",
950 IfExpressionWithNoElse => "if missing an else returns ()",
951 EquatePredicate => "equality where clause is satisfied",
952 MainFunctionType => "`main` function has the correct type",
953 StartFunctionType => "`start` function has the correct type",
954 IntrinsicType => "intrinsic has the correct type",
955 MethodReceiver => "method receiver has the correct type",
956 _ => "types are compatible",