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.
60 use super::SubregionOrigin;
61 use super::RegionVariableOrigin;
62 use super::ValuePairs;
63 use super::region_inference::RegionResolutionError;
64 use super::region_inference::ConcreteFailure;
65 use super::region_inference::SubSupConflict;
66 use super::region_inference::GenericBoundFailure;
67 use super::region_inference::GenericKind;
68 use super::region_inference::ProcessedErrors;
69 use super::region_inference::ProcessedErrorOrigin;
70 use super::region_inference::SameRegions;
72 use hir::map as hir_map;
75 use hir::def_id::DefId;
78 use traits::{ObligationCause, ObligationCauseCode};
79 use ty::{self, TyCtxt, TypeFoldable};
80 use ty::{Region, ReFree, Issue32330};
81 use ty::error::TypeError;
85 use syntax_pos::{Pos, Span};
86 use errors::DiagnosticBuilder;
88 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
89 pub fn note_and_explain_region(self,
90 err: &mut DiagnosticBuilder,
92 region: &'tcx ty::Region,
94 fn item_scope_tag(item: &hir::Item) -> &'static str {
96 hir::ItemImpl(..) => "impl",
97 hir::ItemStruct(..) => "struct",
98 hir::ItemUnion(..) => "union",
99 hir::ItemEnum(..) => "enum",
100 hir::ItemTrait(..) => "trait",
101 hir::ItemFn(..) => "function body",
106 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
108 hir::TraitItemKind::Method(..) => "method body",
109 hir::TraitItemKind::Const(..) |
110 hir::TraitItemKind::Type(..) => "associated item"
114 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
116 hir::ImplItemKind::Method(..) => "method body",
117 hir::ImplItemKind::Const(..) |
118 hir::ImplItemKind::Type(_) => "associated item"
122 fn explain_span<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
123 heading: &str, span: Span)
124 -> (String, Option<Span>) {
125 let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
126 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
130 let (description, span) = match *region {
131 ty::ReScope(scope) => {
133 let unknown_scope = || {
134 format!("{}unknown scope: {:?}{}. Please report a bug.",
135 prefix, scope, suffix)
137 let span = match scope.span(&self.region_maps, &self.hir) {
140 err.note(&unknown_scope());
144 let tag = match self.hir.find(scope.node_id(&self.region_maps)) {
145 Some(hir_map::NodeBlock(_)) => "block",
146 Some(hir_map::NodeExpr(expr)) => match expr.node {
147 hir::ExprCall(..) => "call",
148 hir::ExprMethodCall(..) => "method call",
149 hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
150 hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) => "while let",
151 hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) => "for",
152 hir::ExprMatch(..) => "match",
155 Some(hir_map::NodeStmt(_)) => "statement",
156 Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
157 Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
158 Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
160 err.span_note(span, &unknown_scope());
164 let scope_decorated_tag = match self.region_maps.code_extent_data(scope) {
165 region::CodeExtentData::Misc(_) => tag,
166 region::CodeExtentData::CallSiteScope { .. } => {
167 "scope of call-site for function"
169 region::CodeExtentData::ParameterScope { .. } => {
170 "scope of function body"
172 region::CodeExtentData::DestructionScope(_) => {
173 new_string = format!("destruction scope surrounding {}", tag);
176 region::CodeExtentData::Remainder(r) => {
177 new_string = format!("block suffix following statement {}",
178 r.first_statement_index);
182 explain_span(self, scope_decorated_tag, span)
185 ty::ReFree(ref fr) => {
186 let prefix = match fr.bound_region {
188 format!("the anonymous lifetime #{} defined on", idx + 1)
190 ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
192 format!("the lifetime {} as defined on",
197 let node = fr.scope.node_id(&self.region_maps);
199 let tag = match self.hir.find(node) {
200 Some(hir_map::NodeBlock(_)) |
201 Some(hir_map::NodeExpr(_)) => "body",
202 Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
203 Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
204 Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
206 // this really should not happen, but it does:
209 unknown = format!("unexpected node ({}) for scope {:?}. \
210 Please report a bug.",
211 self.hir.node_to_string(node), fr.scope);
215 unknown = format!("unknown node for scope {:?}. \
216 Please report a bug.", fr.scope);
220 let (msg, opt_span) = explain_span(self, tag, self.hir.span(node));
221 (format!("{} {}", prefix, msg), opt_span)
224 ty::ReStatic => ("the static lifetime".to_owned(), None),
226 ty::ReEmpty => ("the empty lifetime".to_owned(), None),
228 ty::ReEarlyBound(ref data) => (data.name.to_string(), None),
230 // FIXME(#13998) ReSkolemized should probably print like
231 // ReFree rather than dumping Debug output on the user.
233 // We shouldn't really be having unification failures with ReVar
234 // and ReLateBound though.
235 ty::ReSkolemized(..) |
237 ty::ReLateBound(..) |
239 (format!("lifetime {:?}", region), None)
242 let message = format!("{}{}{}", prefix, description, suffix);
243 if let Some(span) = span {
244 err.span_note(span, &message);
251 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
252 pub fn report_region_errors(&self,
253 errors: &Vec<RegionResolutionError<'tcx>>) {
254 debug!("report_region_errors(): {} errors to start", errors.len());
256 // try to pre-process the errors, which will group some of them
257 // together into a `ProcessedErrors` group:
258 let processed_errors = self.process_errors(errors);
259 let errors = processed_errors.as_ref().unwrap_or(errors);
261 debug!("report_region_errors: {} errors after preprocessing", errors.len());
263 for error in errors {
264 debug!("report_region_errors: error = {:?}", error);
265 match error.clone() {
266 ConcreteFailure(origin, sub, sup) => {
267 self.report_concrete_failure(origin, sub, sup).emit();
270 GenericBoundFailure(kind, param_ty, sub) => {
271 self.report_generic_bound_failure(kind, param_ty, sub);
274 SubSupConflict(var_origin,
276 sup_origin, sup_r) => {
277 self.report_sub_sup_conflict(var_origin,
282 ProcessedErrors(ref origins,
283 ref same_regions) => {
284 if !same_regions.is_empty() {
285 self.report_processed_errors(origins);
292 // This method goes through all the errors and try to group certain types
293 // of error together, for the purpose of suggesting explicit lifetime
294 // parameters to the user. This is done so that we can have a more
295 // complete view of what lifetimes should be the same.
296 // If the return value is an empty vector, it means that processing
297 // failed (so the return value of this method should not be used).
299 // The method also attempts to weed out messages that seem like
300 // duplicates that will be unhelpful to the end-user. But
301 // obviously it never weeds out ALL errors.
302 fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
303 -> Option<Vec<RegionResolutionError<'tcx>>> {
304 debug!("process_errors()");
305 let mut origins = Vec::new();
307 // we collect up ConcreteFailures and SubSupConflicts that are
308 // relating free-regions bound on the fn-header and group them
309 // together into this vector
310 let mut same_regions = Vec::new();
312 // here we put errors that we will not be able to process nicely
313 let mut other_errors = Vec::new();
315 // we collect up GenericBoundFailures in here.
316 let mut bound_failures = Vec::new();
318 for error in errors {
319 // Check whether we can process this error into some other
320 // form; if not, fall through.
322 ConcreteFailure(ref origin, sub, sup) => {
323 debug!("processing ConcreteFailure");
324 if let SubregionOrigin::CompareImplMethodObligation { .. } = *origin {
325 // When comparing an impl method against a
326 // trait method, it is not helpful to suggest
327 // changes to the impl method. This is
328 // because the impl method signature is being
329 // checked using the trait's environment, so
330 // usually the changes we suggest would
331 // actually have to be applied to the *trait*
332 // method (and it's not clear that the trait
333 // method is even under the user's control).
334 } else if let Some(same_frs) = free_regions_from_same_fn(self.tcx, sub, sup) {
336 ProcessedErrorOrigin::ConcreteFailure(
340 append_to_same_regions(&mut same_regions, &same_frs);
344 SubSupConflict(ref var_origin, ref sub_origin, sub, ref sup_origin, sup) => {
345 debug!("processing SubSupConflict sub: {:?} sup: {:?}", sub, sup);
346 match (sub_origin, sup_origin) {
347 (&SubregionOrigin::CompareImplMethodObligation { .. }, _) => {
348 // As above, when comparing an impl method
349 // against a trait method, it is not helpful
350 // to suggest changes to the impl method.
352 (_, &SubregionOrigin::CompareImplMethodObligation { .. }) => {
356 if let Some(same_frs) = free_regions_from_same_fn(self.tcx, sub, sup) {
358 ProcessedErrorOrigin::VariableFailure(
359 var_origin.clone()));
360 append_to_same_regions(&mut same_regions, &same_frs);
366 GenericBoundFailure(ref origin, ref kind, region) => {
367 bound_failures.push((origin.clone(), kind.clone(), region));
370 ProcessedErrors(..) => {
371 bug!("should not encounter a `ProcessedErrors` yet: {:?}", error)
375 // No changes to this error.
376 other_errors.push(error.clone());
379 // ok, let's pull together the errors, sorted in an order that
380 // we think will help user the best
381 let mut processed_errors = vec![];
383 // first, put the processed errors, if any
384 if !same_regions.is_empty() {
385 let common_scope_id = same_regions[0].scope_id;
386 for sr in &same_regions {
387 // Since ProcessedErrors is used to reconstruct the function
388 // declaration, we want to make sure that they are, in fact,
389 // from the same scope
390 if sr.scope_id != common_scope_id {
391 debug!("returning empty result from process_errors because
392 {} != {}", sr.scope_id, common_scope_id);
396 assert!(origins.len() > 0);
397 let pe = ProcessedErrors(origins, same_regions);
398 debug!("errors processed: {:?}", pe);
399 processed_errors.push(pe);
402 // next, put the other misc errors
403 processed_errors.extend(other_errors);
405 // finally, put the `T: 'a` errors, but only if there were no
406 // other errors. otherwise, these have a very high rate of
407 // being unhelpful in practice. This is because they are
408 // basically secondary checks that test the state of the
409 // region graph after the rest of inference is done, and the
410 // other kinds of errors indicate that the region constraint
411 // graph is internally inconsistent, so these test results are
412 // likely to be meaningless.
413 if processed_errors.is_empty() {
414 for (origin, kind, region) in bound_failures {
415 processed_errors.push(GenericBoundFailure(origin, kind, region));
419 // we should always wind up with SOME errors, unless there were no
421 assert!(if errors.len() > 0 {processed_errors.len() > 0} else {true});
423 return Some(processed_errors);
426 struct FreeRegionsFromSameFn {
427 sub_fr: ty::FreeRegion,
428 sup_fr: ty::FreeRegion,
429 scope_id: ast::NodeId
432 impl FreeRegionsFromSameFn {
433 fn new(sub_fr: ty::FreeRegion,
434 sup_fr: ty::FreeRegion,
435 scope_id: ast::NodeId)
436 -> FreeRegionsFromSameFn {
437 FreeRegionsFromSameFn {
445 fn free_regions_from_same_fn<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
448 -> Option<FreeRegionsFromSameFn> {
449 debug!("free_regions_from_same_fn(sub={:?}, sup={:?})", sub, sup);
450 let (scope_id, fr1, fr2) = match (sub, sup) {
451 (&ReFree(fr1), &ReFree(fr2)) => {
452 if fr1.scope != fr2.scope {
455 assert!(fr1.scope == fr2.scope);
456 (fr1.scope.node_id(&tcx.region_maps), fr1, fr2)
460 let parent = tcx.hir.get_parent(scope_id);
461 let parent_node = tcx.hir.find(parent);
463 Some(node) => match node {
464 hir_map::NodeItem(item) => match item.node {
466 Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
470 hir_map::NodeImplItem(..) |
471 hir_map::NodeTraitItem(..) => {
472 Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
477 debug!("no parent node of scope_id {}", scope_id);
483 fn append_to_same_regions(same_regions: &mut Vec<SameRegions>,
484 same_frs: &FreeRegionsFromSameFn) {
485 debug!("append_to_same_regions(same_regions={:?}, same_frs={:?})",
486 same_regions, same_frs);
487 let scope_id = same_frs.scope_id;
488 let (sub_fr, sup_fr) = (same_frs.sub_fr, same_frs.sup_fr);
489 for sr in same_regions.iter_mut() {
490 if sr.contains(&sup_fr.bound_region) && scope_id == sr.scope_id {
491 sr.push(sub_fr.bound_region);
495 same_regions.push(SameRegions {
497 regions: vec![sub_fr.bound_region, sup_fr.bound_region]
502 /// Adds a note if the types come from similarly named crates
503 fn check_and_note_conflicting_crates(&self,
504 err: &mut DiagnosticBuilder,
505 terr: &TypeError<'tcx>,
507 let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
508 // Only external crates, if either is from a local
509 // module we could have false positives
510 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
511 let exp_path = self.tcx.item_path_str(did1);
512 let found_path = self.tcx.item_path_str(did2);
513 // We compare strings because DefPath can be different
514 // for imported and non-imported crates
515 if exp_path == found_path {
516 let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
517 err.span_note(sp, &format!("Perhaps two different versions \
518 of crate `{}` are being used?",
524 TypeError::Sorts(ref exp_found) => {
525 // if they are both "path types", there's a chance of ambiguity
526 // due to different versions of the same crate
527 match (&exp_found.expected.sty, &exp_found.found.sty) {
528 (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
529 report_path_match(err, exp_adt.did, found_adt.did);
534 TypeError::Traits(ref exp_found) => {
535 report_path_match(err, exp_found.expected, exp_found.found);
537 _ => () // FIXME(#22750) handle traits and stuff
541 fn note_error_origin(&self,
542 err: &mut DiagnosticBuilder<'tcx>,
543 cause: &ObligationCause<'tcx>)
546 ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
547 hir::MatchSource::IfLetDesugar {..} => {
548 err.span_note(arm_span, "`if let` arm with an incompatible type");
551 err.span_note(arm_span, "match arm with an incompatible type");
558 pub fn note_type_err(&self,
559 diag: &mut DiagnosticBuilder<'tcx>,
560 cause: &ObligationCause<'tcx>,
561 secondary_span: Option<(Span, String)>,
562 values: Option<ValuePairs<'tcx>>,
563 terr: &TypeError<'tcx>)
565 let expected_found = match values {
567 Some(values) => match self.values_str(&values) {
568 Some((expected, found)) => Some((expected, found)),
570 // Derived error. Cancel the emitter.
571 self.tcx.sess.diagnostic().cancel(diag);
577 let span = cause.span;
579 if let Some((expected, found)) = expected_found {
580 let is_simple_error = if let &TypeError::Sorts(ref values) = terr {
581 values.expected.is_primitive() && values.found.is_primitive()
586 if !is_simple_error {
587 if expected == found {
588 if let &TypeError::Sorts(ref values) = terr {
589 diag.note_expected_found_extra(
590 &"type", &expected, &found,
591 &format!(" ({})", values.expected.sort_string(self.tcx)),
592 &format!(" ({})", values.found.sort_string(self.tcx)));
594 diag.note_expected_found(&"type", &expected, &found);
597 diag.note_expected_found(&"type", &expected, &found);
602 diag.span_label(span, &terr);
603 if let Some((sp, msg)) = secondary_span {
604 diag.span_label(sp, &msg);
607 self.note_error_origin(diag, &cause);
608 self.check_and_note_conflicting_crates(diag, terr, span);
609 self.tcx.note_and_explain_type_err(diag, terr, span);
612 pub fn note_issue_32330(&self,
613 diag: &mut DiagnosticBuilder<'tcx>,
614 terr: &TypeError<'tcx>)
616 debug!("note_issue_32330: terr={:?}", terr);
618 TypeError::RegionsInsufficientlyPolymorphic(_, &Region::ReVar(vid)) |
619 TypeError::RegionsOverlyPolymorphic(_, &Region::ReVar(vid)) => {
620 match self.region_vars.var_origin(vid) {
621 RegionVariableOrigin::EarlyBoundRegion(_, _, Some(Issue32330 {
626 &format!("lifetime parameter `{0}` declared on fn `{1}` \
627 appears only in the return type, \
628 but here is required to be higher-ranked, \
629 which means that `{0}` must appear in both \
630 argument and return types",
632 self.tcx.item_path_str(fn_def_id)));
634 &format!("this error is the result of a recent bug fix; \
635 for more information, see issue #33685 \
636 <https://github.com/rust-lang/rust/issues/33685>"));
645 pub fn report_and_explain_type_error(&self,
646 trace: TypeTrace<'tcx>,
647 terr: &TypeError<'tcx>)
648 -> DiagnosticBuilder<'tcx>
650 let span = trace.cause.span;
651 let failure_str = trace.cause.as_failure_str();
652 let mut diag = match trace.cause.code {
653 ObligationCauseCode::IfExpressionWithNoElse => {
654 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
656 ObligationCauseCode::MainFunctionType => {
657 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
660 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
663 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
664 self.note_issue_32330(&mut diag, terr);
668 /// Returns a string of the form "expected `{}`, found `{}`".
669 fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<(String, String)> {
671 infer::Types(ref exp_found) => self.expected_found_str(exp_found),
672 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
673 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
677 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
679 exp_found: &ty::error::ExpectedFound<T>)
680 -> Option<(String, String)>
682 let exp_found = self.resolve_type_vars_if_possible(exp_found);
683 if exp_found.references_error() {
687 Some((format!("{}", exp_found.expected), format!("{}", exp_found.found)))
690 fn report_generic_bound_failure(&self,
691 origin: SubregionOrigin<'tcx>,
692 bound_kind: GenericKind<'tcx>,
695 // FIXME: it would be better to report the first error message
696 // with the span of the parameter itself, rather than the span
697 // where the error was detected. But that span is not readily
700 let labeled_user_string = match bound_kind {
701 GenericKind::Param(ref p) =>
702 format!("the parameter type `{}`", p),
703 GenericKind::Projection(ref p) =>
704 format!("the associated type `{}`", p),
707 if let SubregionOrigin::CompareImplMethodObligation {
708 span, item_name, impl_item_def_id, trait_item_def_id, lint_id
710 self.report_extra_impl_obligation(span,
714 &format!("`{}: {}`", bound_kind, sub),
720 let mut err = match *sub {
721 ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
722 // Does the required lifetime have a nice name we can print?
723 let mut err = struct_span_err!(self.tcx.sess,
726 "{} may not live long enough",
727 labeled_user_string);
728 err.help(&format!("consider adding an explicit lifetime bound `{}: {}`...",
735 // Does the required lifetime have a nice name we can print?
736 let mut err = struct_span_err!(self.tcx.sess,
739 "{} may not live long enough",
740 labeled_user_string);
741 err.help(&format!("consider adding an explicit lifetime \
742 bound `{}: 'static`...",
748 // If not, be less specific.
749 let mut err = struct_span_err!(self.tcx.sess,
752 "{} may not live long enough",
753 labeled_user_string);
754 err.help(&format!("consider adding an explicit lifetime bound for `{}`",
756 self.tcx.note_and_explain_region(
758 &format!("{} must be valid for ", labeled_user_string),
765 self.note_region_origin(&mut err, &origin);
769 fn report_concrete_failure(&self,
770 origin: SubregionOrigin<'tcx>,
773 -> DiagnosticBuilder<'tcx> {
775 infer::Subtype(trace) => {
776 let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
777 self.report_and_explain_type_error(trace, &terr)
779 infer::Reborrow(span) => {
780 let mut err = struct_span_err!(self.tcx.sess, span, E0312,
781 "lifetime of reference outlives \
782 lifetime of borrowed content...");
783 self.tcx.note_and_explain_region(&mut err,
784 "...the reference is valid for ",
787 self.tcx.note_and_explain_region(&mut err,
788 "...but the borrowed content is only valid for ",
793 infer::ReborrowUpvar(span, ref upvar_id) => {
794 let mut err = struct_span_err!(self.tcx.sess, span, E0313,
795 "lifetime of borrowed pointer outlives \
796 lifetime of captured variable `{}`...",
797 self.tcx.local_var_name_str(upvar_id.var_id));
798 self.tcx.note_and_explain_region(&mut err,
799 "...the borrowed pointer is valid for ",
802 self.tcx.note_and_explain_region(&mut err,
803 &format!("...but `{}` is only valid for ",
804 self.tcx.local_var_name_str(upvar_id.var_id)),
809 infer::InfStackClosure(span) => {
810 let mut err = struct_span_err!(self.tcx.sess, span, E0314,
811 "closure outlives stack frame");
812 self.tcx.note_and_explain_region(&mut err,
813 "...the closure must be valid for ",
816 self.tcx.note_and_explain_region(&mut err,
817 "...but the closure's stack frame is only valid for ",
822 infer::InvokeClosure(span) => {
823 let mut err = struct_span_err!(self.tcx.sess, span, E0315,
824 "cannot invoke closure outside of its lifetime");
825 self.tcx.note_and_explain_region(&mut err,
826 "the closure is only valid for ",
831 infer::DerefPointer(span) => {
832 let mut err = struct_span_err!(self.tcx.sess, span, E0473,
833 "dereference of reference outside its lifetime");
834 self.tcx.note_and_explain_region(&mut err,
835 "the reference is only valid for ",
840 infer::FreeVariable(span, id) => {
841 let mut err = struct_span_err!(self.tcx.sess, span, E0474,
842 "captured variable `{}` does not outlive the enclosing closure",
843 self.tcx.local_var_name_str(id));
844 self.tcx.note_and_explain_region(&mut err,
845 "captured variable is valid for ",
848 self.tcx.note_and_explain_region(&mut err,
849 "closure is valid for ",
854 infer::IndexSlice(span) => {
855 let mut err = struct_span_err!(self.tcx.sess, span, E0475,
856 "index of slice outside its lifetime");
857 self.tcx.note_and_explain_region(&mut err,
858 "the slice is only valid for ",
863 infer::RelateObjectBound(span) => {
864 let mut err = struct_span_err!(self.tcx.sess, span, E0476,
865 "lifetime of the source pointer does not outlive \
866 lifetime bound of the object type");
867 self.tcx.note_and_explain_region(&mut err,
868 "object type is valid for ",
871 self.tcx.note_and_explain_region(&mut err,
872 "source pointer is only valid for ",
877 infer::RelateParamBound(span, ty) => {
878 let mut err = struct_span_err!(self.tcx.sess, span, E0477,
879 "the type `{}` does not fulfill the required lifetime",
880 self.ty_to_string(ty));
881 self.tcx.note_and_explain_region(&mut err,
882 "type must outlive ",
887 infer::RelateRegionParamBound(span) => {
888 let mut err = struct_span_err!(self.tcx.sess, span, E0478,
889 "lifetime bound not satisfied");
890 self.tcx.note_and_explain_region(&mut err,
891 "lifetime parameter instantiated with ",
894 self.tcx.note_and_explain_region(&mut err,
895 "but lifetime parameter must outlive ",
900 infer::RelateDefaultParamBound(span, ty) => {
901 let mut err = struct_span_err!(self.tcx.sess, span, E0479,
902 "the type `{}` (provided as the value of \
903 a type parameter) is not valid at this point",
904 self.ty_to_string(ty));
905 self.tcx.note_and_explain_region(&mut err,
906 "type must outlive ",
911 infer::CallRcvr(span) => {
912 let mut err = struct_span_err!(self.tcx.sess, span, E0480,
913 "lifetime of method receiver does not outlive \
915 self.tcx.note_and_explain_region(&mut err,
916 "the receiver is only valid for ",
921 infer::CallArg(span) => {
922 let mut err = struct_span_err!(self.tcx.sess, span, E0481,
923 "lifetime of function argument does not outlive \
925 self.tcx.note_and_explain_region(&mut err,
926 "the function argument is only valid for ",
931 infer::CallReturn(span) => {
932 let mut err = struct_span_err!(self.tcx.sess, span, E0482,
933 "lifetime of return value does not outlive \
935 self.tcx.note_and_explain_region(&mut err,
936 "the return value is only valid for ",
941 infer::Operand(span) => {
942 let mut err = struct_span_err!(self.tcx.sess, span, E0483,
943 "lifetime of operand does not outlive \
945 self.tcx.note_and_explain_region(&mut err,
946 "the operand is only valid for ",
951 infer::AddrOf(span) => {
952 let mut err = struct_span_err!(self.tcx.sess, span, E0484,
953 "reference is not valid at the time of borrow");
954 self.tcx.note_and_explain_region(&mut err,
955 "the borrow is only valid for ",
960 infer::AutoBorrow(span) => {
961 let mut err = struct_span_err!(self.tcx.sess, span, E0485,
962 "automatically reference is not valid \
963 at the time of borrow");
964 self.tcx.note_and_explain_region(&mut err,
965 "the automatic borrow is only valid for ",
970 infer::ExprTypeIsNotInScope(t, span) => {
971 let mut err = struct_span_err!(self.tcx.sess, span, E0486,
972 "type of expression contains references \
973 that are not valid during the expression: `{}`",
974 self.ty_to_string(t));
975 self.tcx.note_and_explain_region(&mut err,
976 "type is only valid for ",
981 infer::SafeDestructor(span) => {
982 let mut err = struct_span_err!(self.tcx.sess, span, E0487,
983 "unsafe use of destructor: destructor might be called \
984 while references are dead");
985 // FIXME (22171): terms "super/subregion" are suboptimal
986 self.tcx.note_and_explain_region(&mut err,
990 self.tcx.note_and_explain_region(&mut err,
996 infer::BindingTypeIsNotValidAtDecl(span) => {
997 let mut err = struct_span_err!(self.tcx.sess, span, E0488,
998 "lifetime of variable does not enclose its declaration");
999 self.tcx.note_and_explain_region(&mut err,
1000 "the variable is only valid for ",
1005 infer::ParameterInScope(_, span) => {
1006 let mut err = struct_span_err!(self.tcx.sess, span, E0489,
1007 "type/lifetime parameter not in scope here");
1008 self.tcx.note_and_explain_region(&mut err,
1009 "the parameter is only valid for ",
1014 infer::DataBorrowed(ty, span) => {
1015 let mut err = struct_span_err!(self.tcx.sess, span, E0490,
1016 "a value of type `{}` is borrowed for too long",
1017 self.ty_to_string(ty));
1018 self.tcx.note_and_explain_region(&mut err, "the type is valid for ", sub, "");
1019 self.tcx.note_and_explain_region(&mut err, "but the borrow lasts for ", sup, "");
1022 infer::ReferenceOutlivesReferent(ty, span) => {
1023 let mut err = struct_span_err!(self.tcx.sess, span, E0491,
1024 "in type `{}`, reference has a longer lifetime \
1025 than the data it references",
1026 self.ty_to_string(ty));
1027 self.tcx.note_and_explain_region(&mut err,
1028 "the pointer is valid for ",
1031 self.tcx.note_and_explain_region(&mut err,
1032 "but the referenced data is only valid for ",
1037 infer::CompareImplMethodObligation { span,
1042 self.report_extra_impl_obligation(span,
1046 &format!("`{}: {}`", sup, sub),
1052 fn report_sub_sup_conflict(&self,
1053 var_origin: RegionVariableOrigin,
1054 sub_origin: SubregionOrigin<'tcx>,
1055 sub_region: &'tcx Region,
1056 sup_origin: SubregionOrigin<'tcx>,
1057 sup_region: &'tcx Region) {
1058 let mut err = self.report_inference_failure(var_origin);
1060 self.tcx.note_and_explain_region(&mut err,
1061 "first, the lifetime cannot outlive ",
1065 self.note_region_origin(&mut err, &sup_origin);
1067 self.tcx.note_and_explain_region(&mut err,
1068 "but, the lifetime must be valid for ",
1072 self.note_region_origin(&mut err, &sub_origin);
1076 fn report_processed_errors(&self,
1077 origins: &[ProcessedErrorOrigin<'tcx>]) {
1078 for origin in origins.iter() {
1079 let mut err = match *origin {
1080 ProcessedErrorOrigin::VariableFailure(ref var_origin) =>
1081 self.report_inference_failure(var_origin.clone()),
1082 ProcessedErrorOrigin::ConcreteFailure(ref sr_origin, sub, sup) =>
1083 self.report_concrete_failure(sr_origin.clone(), sub, sup),
1091 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1092 fn report_inference_failure(&self,
1093 var_origin: RegionVariableOrigin)
1094 -> DiagnosticBuilder<'tcx> {
1095 let br_string = |br: ty::BoundRegion| {
1096 let mut s = br.to_string();
1102 let var_description = match var_origin {
1103 infer::MiscVariable(_) => "".to_string(),
1104 infer::PatternRegion(_) => " for pattern".to_string(),
1105 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1106 infer::Autoref(_) => " for autoref".to_string(),
1107 infer::Coercion(_) => " for automatic coercion".to_string(),
1108 infer::LateBoundRegion(_, br, infer::FnCall) => {
1109 format!(" for lifetime parameter {}in function call",
1112 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1113 format!(" for lifetime parameter {}in generic type", br_string(br))
1115 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
1116 format!(" for lifetime parameter {}in trait containing associated type `{}`",
1117 br_string(br), type_name)
1119 infer::EarlyBoundRegion(_, name, _) => {
1120 format!(" for lifetime parameter `{}`",
1123 infer::BoundRegionInCoherence(name) => {
1124 format!(" for lifetime parameter `{}` in coherence check",
1127 infer::UpvarRegion(ref upvar_id, _) => {
1128 format!(" for capture of `{}` by closure",
1129 self.tcx.local_var_name_str(upvar_id.var_id).to_string())
1133 struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
1134 "cannot infer an appropriate lifetime{} \
1135 due to conflicting requirements",
1139 fn note_region_origin(&self, err: &mut DiagnosticBuilder, origin: &SubregionOrigin<'tcx>) {
1141 infer::Subtype(ref trace) => {
1142 if let Some((expected, found)) = self.values_str(&trace.values) {
1143 // FIXME: do we want a "the" here?
1146 &format!("...so that {} (expected {}, found {})",
1147 trace.cause.as_requirement_str(), expected, found));
1149 // FIXME: this really should be handled at some earlier stage. Our
1150 // handling of region checking when type errors are present is
1155 &format!("...so that {}",
1156 trace.cause.as_requirement_str()));
1159 infer::Reborrow(span) => {
1162 "...so that reference does not outlive \
1165 infer::ReborrowUpvar(span, ref upvar_id) => {
1169 "...so that closure can access `{}`",
1170 self.tcx.local_var_name_str(upvar_id.var_id)
1173 infer::InfStackClosure(span) => {
1176 "...so that closure does not outlive its stack frame");
1178 infer::InvokeClosure(span) => {
1181 "...so that closure is not invoked outside its lifetime");
1183 infer::DerefPointer(span) => {
1186 "...so that pointer is not dereferenced \
1187 outside its lifetime");
1189 infer::FreeVariable(span, id) => {
1192 &format!("...so that captured variable `{}` \
1193 does not outlive the enclosing closure",
1194 self.tcx.local_var_name_str(id)));
1196 infer::IndexSlice(span) => {
1199 "...so that slice is not indexed outside the lifetime");
1201 infer::RelateObjectBound(span) => {
1204 "...so that it can be closed over into an object");
1206 infer::CallRcvr(span) => {
1209 "...so that method receiver is valid for the method call");
1211 infer::CallArg(span) => {
1214 "...so that argument is valid for the call");
1216 infer::CallReturn(span) => {
1219 "...so that return value is valid for the call");
1221 infer::Operand(span) => {
1224 "...so that operand is valid for operation");
1226 infer::AddrOf(span) => {
1229 "...so that reference is valid \
1230 at the time of borrow");
1232 infer::AutoBorrow(span) => {
1235 "...so that auto-reference is valid \
1236 at the time of borrow");
1238 infer::ExprTypeIsNotInScope(t, span) => {
1241 &format!("...so type `{}` of expression is valid during the \
1243 self.ty_to_string(t)));
1245 infer::BindingTypeIsNotValidAtDecl(span) => {
1248 "...so that variable is valid at time of its declaration");
1250 infer::ParameterInScope(_, span) => {
1253 "...so that a type/lifetime parameter is in scope here");
1255 infer::DataBorrowed(ty, span) => {
1258 &format!("...so that the type `{}` is not borrowed for too long",
1259 self.ty_to_string(ty)));
1261 infer::ReferenceOutlivesReferent(ty, span) => {
1264 &format!("...so that the reference type `{}` \
1265 does not outlive the data it points at",
1266 self.ty_to_string(ty)));
1268 infer::RelateParamBound(span, t) => {
1271 &format!("...so that the type `{}` \
1272 will meet its required lifetime bounds",
1273 self.ty_to_string(t)));
1275 infer::RelateDefaultParamBound(span, t) => {
1278 &format!("...so that type parameter \
1279 instantiated with `{}`, \
1280 will meet its declared lifetime bounds",
1281 self.ty_to_string(t)));
1283 infer::RelateRegionParamBound(span) => {
1286 "...so that the declared lifetime parameter bounds \
1289 infer::SafeDestructor(span) => {
1292 "...so that references are valid when the destructor \
1295 infer::CompareImplMethodObligation { span, .. } => {
1298 "...so that the definition in impl matches the definition from the trait");
1304 impl<'tcx> ObligationCause<'tcx> {
1305 fn as_failure_str(&self) -> &'static str {
1306 use traits::ObligationCauseCode::*;
1308 CompareImplMethodObligation { .. } => "method not compatible with trait",
1309 MatchExpressionArm { source, .. } => match source {
1310 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
1311 _ => "match arms have incompatible types",
1313 IfExpression => "if and else have incompatible types",
1314 IfExpressionWithNoElse => "if may be missing an else clause",
1315 EquatePredicate => "equality predicate not satisfied",
1316 MainFunctionType => "main function has wrong type",
1317 StartFunctionType => "start function has wrong type",
1318 IntrinsicType => "intrinsic has wrong type",
1319 MethodReceiver => "mismatched method receiver",
1320 _ => "mismatched types",
1324 fn as_requirement_str(&self) -> &'static str {
1325 use traits::ObligationCauseCode::*;
1327 CompareImplMethodObligation { .. } => "method type is compatible with trait",
1328 ExprAssignable => "expression is assignable",
1329 MatchExpressionArm { source, .. } => match source {
1330 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have compatible types",
1331 _ => "match arms have compatible types",
1333 IfExpression => "if and else have compatible types",
1334 IfExpressionWithNoElse => "if missing an else returns ()",
1335 EquatePredicate => "equality where clause is satisfied",
1336 MainFunctionType => "`main` function has the correct type",
1337 StartFunctionType => "`start` function has the correct type",
1338 IntrinsicType => "intrinsic has the correct type",
1339 MethodReceiver => "method receiver has the correct type",
1340 _ => "types are compatible",