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;
76 use hir::def_id::DefId;
79 use traits::{ObligationCause, ObligationCauseCode};
80 use ty::{self, TyCtxt, TypeFoldable};
81 use ty::{Region, ReFree};
82 use ty::error::TypeError;
86 use syntax_pos::{Pos, Span};
87 use errors::DiagnosticBuilder;
89 impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
90 pub fn note_and_explain_region(self,
91 err: &mut DiagnosticBuilder,
93 region: &'tcx ty::Region,
95 fn item_scope_tag(item: &hir::Item) -> &'static str {
97 hir::ItemImpl(..) => "impl",
98 hir::ItemStruct(..) => "struct",
99 hir::ItemUnion(..) => "union",
100 hir::ItemEnum(..) => "enum",
101 hir::ItemTrait(..) => "trait",
102 hir::ItemFn(..) => "function body",
107 fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
109 hir::TraitItemKind::Method(..) => "method body",
110 hir::TraitItemKind::Const(..) |
111 hir::TraitItemKind::Type(..) => "associated item"
115 fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
117 hir::ImplItemKind::Method(..) => "method body",
118 hir::ImplItemKind::Const(..) |
119 hir::ImplItemKind::Type(_) => "associated item"
123 fn explain_span<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
124 heading: &str, span: Span)
125 -> (String, Option<Span>) {
126 let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
127 (format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
131 let (description, span) = match *region {
132 ty::ReScope(scope) => {
134 let unknown_scope = || {
135 format!("{}unknown scope: {:?}{}. Please report a bug.",
136 prefix, scope, suffix)
138 let span = match scope.span(&self.region_maps, &self.hir) {
141 err.note(&unknown_scope());
145 let tag = match self.hir.find(scope.node_id(&self.region_maps)) {
146 Some(hir_map::NodeBlock(_)) => "block",
147 Some(hir_map::NodeExpr(expr)) => match expr.node {
148 hir::ExprCall(..) => "call",
149 hir::ExprMethodCall(..) => "method call",
150 hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
151 hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) => "while let",
152 hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) => "for",
153 hir::ExprMatch(..) => "match",
156 Some(hir_map::NodeStmt(_)) => "statement",
157 Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
158 Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
159 Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
161 err.span_note(span, &unknown_scope());
165 let scope_decorated_tag = match self.region_maps.code_extent_data(scope) {
166 region::CodeExtentData::Misc(_) => tag,
167 region::CodeExtentData::CallSiteScope { .. } => {
168 "scope of call-site for function"
170 region::CodeExtentData::ParameterScope { .. } => {
171 "scope of function body"
173 region::CodeExtentData::DestructionScope(_) => {
174 new_string = format!("destruction scope surrounding {}", tag);
177 region::CodeExtentData::Remainder(r) => {
178 new_string = format!("block suffix following statement {}",
179 r.first_statement_index);
183 explain_span(self, scope_decorated_tag, span)
186 ty::ReFree(ref fr) => {
187 let prefix = match fr.bound_region {
189 format!("the anonymous lifetime #{} defined on", idx + 1)
191 ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
193 format!("the lifetime {} as defined on",
198 let node = fr.scope.node_id(&self.region_maps);
200 let tag = match self.hir.find(node) {
201 Some(hir_map::NodeBlock(_)) |
202 Some(hir_map::NodeExpr(_)) => "body",
203 Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
204 Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
205 Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
207 // this really should not happen, but it does:
210 unknown = format!("unexpected node ({}) for scope {:?}. \
211 Please report a bug.",
212 self.hir.node_to_string(node), fr.scope);
216 unknown = format!("unknown node for scope {:?}. \
217 Please report a bug.", fr.scope);
221 let (msg, opt_span) = explain_span(self, tag, self.hir.span(node));
222 (format!("{} {}", prefix, msg), opt_span)
225 ty::ReStatic => ("the static lifetime".to_owned(), None),
227 ty::ReEmpty => ("the empty lifetime".to_owned(), None),
229 ty::ReEarlyBound(ref data) => (data.name.to_string(), None),
231 // FIXME(#13998) ReSkolemized should probably print like
232 // ReFree rather than dumping Debug output on the user.
234 // We shouldn't really be having unification failures with ReVar
235 // and ReLateBound though.
236 ty::ReSkolemized(..) |
238 ty::ReLateBound(..) |
240 (format!("lifetime {:?}", region), None)
243 let message = format!("{}{}{}", prefix, description, suffix);
244 if let Some(span) = span {
245 err.span_note(span, &message);
252 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
253 pub fn report_region_errors(&self,
254 errors: &Vec<RegionResolutionError<'tcx>>) {
255 debug!("report_region_errors(): {} errors to start", errors.len());
257 // try to pre-process the errors, which will group some of them
258 // together into a `ProcessedErrors` group:
259 let processed_errors = self.process_errors(errors);
260 let errors = processed_errors.as_ref().unwrap_or(errors);
262 debug!("report_region_errors: {} errors after preprocessing", errors.len());
264 for error in errors {
265 debug!("report_region_errors: error = {:?}", error);
266 match error.clone() {
267 ConcreteFailure(origin, sub, sup) => {
268 self.report_concrete_failure(origin, sub, sup).emit();
271 GenericBoundFailure(kind, param_ty, sub) => {
272 self.report_generic_bound_failure(kind, param_ty, sub);
275 SubSupConflict(var_origin,
277 sup_origin, sup_r) => {
278 self.report_sub_sup_conflict(var_origin,
283 ProcessedErrors(ref origins,
284 ref same_regions) => {
285 if !same_regions.is_empty() {
286 self.report_processed_errors(origins);
293 // This method goes through all the errors and try to group certain types
294 // of error together, for the purpose of suggesting explicit lifetime
295 // parameters to the user. This is done so that we can have a more
296 // complete view of what lifetimes should be the same.
297 // If the return value is an empty vector, it means that processing
298 // failed (so the return value of this method should not be used).
300 // The method also attempts to weed out messages that seem like
301 // duplicates that will be unhelpful to the end-user. But
302 // obviously it never weeds out ALL errors.
303 fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
304 -> Option<Vec<RegionResolutionError<'tcx>>> {
305 debug!("process_errors()");
306 let mut origins = Vec::new();
308 // we collect up ConcreteFailures and SubSupConflicts that are
309 // relating free-regions bound on the fn-header and group them
310 // together into this vector
311 let mut same_regions = Vec::new();
313 // here we put errors that we will not be able to process nicely
314 let mut other_errors = Vec::new();
316 // we collect up GenericBoundFailures in here.
317 let mut bound_failures = Vec::new();
319 for error in errors {
320 // Check whether we can process this error into some other
321 // form; if not, fall through.
323 ConcreteFailure(ref origin, sub, sup) => {
324 debug!("processing ConcreteFailure");
325 if let SubregionOrigin::CompareImplMethodObligation { .. } = *origin {
326 // When comparing an impl method against a
327 // trait method, it is not helpful to suggest
328 // changes to the impl method. This is
329 // because the impl method signature is being
330 // checked using the trait's environment, so
331 // usually the changes we suggest would
332 // actually have to be applied to the *trait*
333 // method (and it's not clear that the trait
334 // method is even under the user's control).
335 } else if let Some(same_frs) = free_regions_from_same_fn(self.tcx, sub, sup) {
337 ProcessedErrorOrigin::ConcreteFailure(
341 append_to_same_regions(&mut same_regions, &same_frs);
345 SubSupConflict(ref var_origin, ref sub_origin, sub, ref sup_origin, sup) => {
346 debug!("processing SubSupConflict sub: {:?} sup: {:?}", sub, sup);
347 match (sub_origin, sup_origin) {
348 (&SubregionOrigin::CompareImplMethodObligation { .. }, _) => {
349 // As above, when comparing an impl method
350 // against a trait method, it is not helpful
351 // to suggest changes to the impl method.
353 (_, &SubregionOrigin::CompareImplMethodObligation { .. }) => {
357 if let Some(same_frs) = free_regions_from_same_fn(self.tcx, sub, sup) {
359 ProcessedErrorOrigin::VariableFailure(
360 var_origin.clone()));
361 append_to_same_regions(&mut same_regions, &same_frs);
367 GenericBoundFailure(ref origin, ref kind, region) => {
368 bound_failures.push((origin.clone(), kind.clone(), region));
371 ProcessedErrors(..) => {
372 bug!("should not encounter a `ProcessedErrors` yet: {:?}", error)
376 // No changes to this error.
377 other_errors.push(error.clone());
380 // ok, let's pull together the errors, sorted in an order that
381 // we think will help user the best
382 let mut processed_errors = vec![];
384 // first, put the processed errors, if any
385 if !same_regions.is_empty() {
386 let common_scope_id = same_regions[0].scope_id;
387 for sr in &same_regions {
388 // Since ProcessedErrors is used to reconstruct the function
389 // declaration, we want to make sure that they are, in fact,
390 // from the same scope
391 if sr.scope_id != common_scope_id {
392 debug!("returning empty result from process_errors because
393 {} != {}", sr.scope_id, common_scope_id);
397 assert!(origins.len() > 0);
398 let pe = ProcessedErrors(origins, same_regions);
399 debug!("errors processed: {:?}", pe);
400 processed_errors.push(pe);
403 // next, put the other misc errors
404 processed_errors.extend(other_errors);
406 // finally, put the `T: 'a` errors, but only if there were no
407 // other errors. otherwise, these have a very high rate of
408 // being unhelpful in practice. This is because they are
409 // basically secondary checks that test the state of the
410 // region graph after the rest of inference is done, and the
411 // other kinds of errors indicate that the region constraint
412 // graph is internally inconsistent, so these test results are
413 // likely to be meaningless.
414 if processed_errors.is_empty() {
415 for (origin, kind, region) in bound_failures {
416 processed_errors.push(GenericBoundFailure(origin, kind, region));
420 // we should always wind up with SOME errors, unless there were no
422 assert!(if errors.len() > 0 {processed_errors.len() > 0} else {true});
424 return Some(processed_errors);
427 struct FreeRegionsFromSameFn {
428 sub_fr: ty::FreeRegion,
429 sup_fr: ty::FreeRegion,
430 scope_id: ast::NodeId
433 impl FreeRegionsFromSameFn {
434 fn new(sub_fr: ty::FreeRegion,
435 sup_fr: ty::FreeRegion,
436 scope_id: ast::NodeId)
437 -> FreeRegionsFromSameFn {
438 FreeRegionsFromSameFn {
446 fn free_regions_from_same_fn<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
449 -> Option<FreeRegionsFromSameFn> {
450 debug!("free_regions_from_same_fn(sub={:?}, sup={:?})", sub, sup);
451 let (scope_id, fr1, fr2) = match (sub, sup) {
452 (&ReFree(fr1), &ReFree(fr2)) => {
453 if fr1.scope != fr2.scope {
456 assert!(fr1.scope == fr2.scope);
457 (fr1.scope.node_id(&tcx.region_maps), fr1, fr2)
461 let parent = tcx.hir.get_parent(scope_id);
462 let parent_node = tcx.hir.find(parent);
464 Some(node) => match node {
465 hir_map::NodeItem(item) => match item.node {
467 Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
471 hir_map::NodeImplItem(..) |
472 hir_map::NodeTraitItem(..) => {
473 Some(FreeRegionsFromSameFn::new(fr1, fr2, scope_id))
478 debug!("no parent node of scope_id {}", scope_id);
484 fn append_to_same_regions(same_regions: &mut Vec<SameRegions>,
485 same_frs: &FreeRegionsFromSameFn) {
486 debug!("append_to_same_regions(same_regions={:?}, same_frs={:?})",
487 same_regions, same_frs);
488 let scope_id = same_frs.scope_id;
489 let (sub_fr, sup_fr) = (same_frs.sub_fr, same_frs.sup_fr);
490 for sr in same_regions.iter_mut() {
491 if sr.contains(&sup_fr.bound_region) && scope_id == sr.scope_id {
492 sr.push(sub_fr.bound_region);
496 same_regions.push(SameRegions {
498 regions: vec![sub_fr.bound_region, sup_fr.bound_region]
503 /// Adds a note if the types come from similarly named crates
504 fn check_and_note_conflicting_crates(&self,
505 err: &mut DiagnosticBuilder,
506 terr: &TypeError<'tcx>,
508 let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
509 // Only external crates, if either is from a local
510 // module we could have false positives
511 if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
512 let exp_path = self.tcx.item_path_str(did1);
513 let found_path = self.tcx.item_path_str(did2);
514 // We compare strings because DefPath can be different
515 // for imported and non-imported crates
516 if exp_path == found_path {
517 let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
518 err.span_note(sp, &format!("Perhaps two different versions \
519 of crate `{}` are being used?",
525 TypeError::Sorts(ref exp_found) => {
526 // if they are both "path types", there's a chance of ambiguity
527 // due to different versions of the same crate
528 match (&exp_found.expected.sty, &exp_found.found.sty) {
529 (&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
530 report_path_match(err, exp_adt.did, found_adt.did);
535 TypeError::Traits(ref exp_found) => {
536 report_path_match(err, exp_found.expected, exp_found.found);
538 _ => () // FIXME(#22750) handle traits and stuff
542 fn note_error_origin(&self,
543 err: &mut DiagnosticBuilder<'tcx>,
544 cause: &ObligationCause<'tcx>)
547 ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
548 hir::MatchSource::IfLetDesugar {..} => {
549 err.span_note(arm_span, "`if let` arm with an incompatible type");
552 err.span_note(arm_span, "match arm with an incompatible type");
559 pub fn note_type_err(&self,
560 diag: &mut DiagnosticBuilder<'tcx>,
561 cause: &ObligationCause<'tcx>,
562 secondary_span: Option<(Span, String)>,
563 values: Option<ValuePairs<'tcx>>,
564 terr: &TypeError<'tcx>)
566 let expected_found = match values {
568 Some(values) => match self.values_str(&values) {
569 Some((expected, found)) => Some((expected, found)),
571 // Derived error. Cancel the emitter.
572 self.tcx.sess.diagnostic().cancel(diag);
578 let span = cause.span;
580 if let Some((expected, found)) = expected_found {
581 let is_simple_error = if let &TypeError::Sorts(ref values) = terr {
582 values.expected.is_primitive() && values.found.is_primitive()
587 if !is_simple_error {
588 if expected == found {
589 if let &TypeError::Sorts(ref values) = terr {
590 diag.note_expected_found_extra(
591 &"type", &expected, &found,
592 &format!(" ({})", values.expected.sort_string(self.tcx)),
593 &format!(" ({})", values.found.sort_string(self.tcx)));
595 diag.note_expected_found(&"type", &expected, &found);
598 diag.note_expected_found(&"type", &expected, &found);
603 diag.span_label(span, &terr);
604 if let Some((sp, msg)) = secondary_span {
605 diag.span_label(sp, &msg);
608 self.note_error_origin(diag, &cause);
609 self.check_and_note_conflicting_crates(diag, terr, span);
610 self.tcx.note_and_explain_type_err(diag, terr, span);
613 pub fn report_and_explain_type_error(&self,
614 trace: TypeTrace<'tcx>,
615 terr: &TypeError<'tcx>)
616 -> DiagnosticBuilder<'tcx>
618 let span = trace.cause.span;
619 let failure_str = trace.cause.as_failure_str();
620 let mut diag = match trace.cause.code {
621 ObligationCauseCode::IfExpressionWithNoElse => {
622 struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
624 ObligationCauseCode::MainFunctionType => {
625 struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
628 struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
631 self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
635 /// Returns a string of the form "expected `{}`, found `{}`".
636 fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<(String, String)> {
638 infer::Types(ref exp_found) => self.expected_found_str(exp_found),
639 infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
640 infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
644 fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
646 exp_found: &ty::error::ExpectedFound<T>)
647 -> Option<(String, String)>
649 let exp_found = self.resolve_type_vars_if_possible(exp_found);
650 if exp_found.references_error() {
654 Some((format!("{}", exp_found.expected), format!("{}", exp_found.found)))
657 fn report_generic_bound_failure(&self,
658 origin: SubregionOrigin<'tcx>,
659 bound_kind: GenericKind<'tcx>,
662 // FIXME: it would be better to report the first error message
663 // with the span of the parameter itself, rather than the span
664 // where the error was detected. But that span is not readily
667 let labeled_user_string = match bound_kind {
668 GenericKind::Param(ref p) =>
669 format!("the parameter type `{}`", p),
670 GenericKind::Projection(ref p) =>
671 format!("the associated type `{}`", p),
674 if let SubregionOrigin::CompareImplMethodObligation {
675 span, item_name, impl_item_def_id, trait_item_def_id, lint_id
677 self.report_extra_impl_obligation(span,
681 &format!("`{}: {}`", bound_kind, sub),
687 let mut err = match *sub {
688 ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
689 // Does the required lifetime have a nice name we can print?
690 let mut err = struct_span_err!(self.tcx.sess,
693 "{} may not live long enough",
694 labeled_user_string);
695 err.help(&format!("consider adding an explicit lifetime bound `{}: {}`...",
702 // Does the required lifetime have a nice name we can print?
703 let mut err = struct_span_err!(self.tcx.sess,
706 "{} may not live long enough",
707 labeled_user_string);
708 err.help(&format!("consider adding an explicit lifetime \
709 bound `{}: 'static`...",
715 // If not, be less specific.
716 let mut err = struct_span_err!(self.tcx.sess,
719 "{} may not live long enough",
720 labeled_user_string);
721 err.help(&format!("consider adding an explicit lifetime bound for `{}`",
723 self.tcx.note_and_explain_region(
725 &format!("{} must be valid for ", labeled_user_string),
732 self.note_region_origin(&mut err, &origin);
736 fn report_concrete_failure(&self,
737 origin: SubregionOrigin<'tcx>,
740 -> DiagnosticBuilder<'tcx> {
742 infer::Subtype(trace) => {
743 let terr = TypeError::RegionsDoesNotOutlive(sup, sub);
744 self.report_and_explain_type_error(trace, &terr)
746 infer::Reborrow(span) => {
747 let mut err = struct_span_err!(self.tcx.sess, span, E0312,
748 "lifetime of reference outlives \
749 lifetime of borrowed content...");
750 self.tcx.note_and_explain_region(&mut err,
751 "...the reference is valid for ",
754 self.tcx.note_and_explain_region(&mut err,
755 "...but the borrowed content is only valid for ",
760 infer::ReborrowUpvar(span, ref upvar_id) => {
761 let mut err = struct_span_err!(self.tcx.sess, span, E0313,
762 "lifetime of borrowed pointer outlives \
763 lifetime of captured variable `{}`...",
764 self.tcx.local_var_name_str(upvar_id.var_id));
765 self.tcx.note_and_explain_region(&mut err,
766 "...the borrowed pointer is valid for ",
769 self.tcx.note_and_explain_region(&mut err,
770 &format!("...but `{}` is only valid for ",
771 self.tcx.local_var_name_str(upvar_id.var_id)),
776 infer::InfStackClosure(span) => {
777 let mut err = struct_span_err!(self.tcx.sess, span, E0314,
778 "closure outlives stack frame");
779 self.tcx.note_and_explain_region(&mut err,
780 "...the closure must be valid for ",
783 self.tcx.note_and_explain_region(&mut err,
784 "...but the closure's stack frame is only valid for ",
789 infer::InvokeClosure(span) => {
790 let mut err = struct_span_err!(self.tcx.sess, span, E0315,
791 "cannot invoke closure outside of its lifetime");
792 self.tcx.note_and_explain_region(&mut err,
793 "the closure is only valid for ",
798 infer::DerefPointer(span) => {
799 let mut err = struct_span_err!(self.tcx.sess, span, E0473,
800 "dereference of reference outside its lifetime");
801 self.tcx.note_and_explain_region(&mut err,
802 "the reference is only valid for ",
807 infer::FreeVariable(span, id) => {
808 let mut err = struct_span_err!(self.tcx.sess, span, E0474,
809 "captured variable `{}` does not outlive the enclosing closure",
810 self.tcx.local_var_name_str(id));
811 self.tcx.note_and_explain_region(&mut err,
812 "captured variable is valid for ",
815 self.tcx.note_and_explain_region(&mut err,
816 "closure is valid for ",
821 infer::IndexSlice(span) => {
822 let mut err = struct_span_err!(self.tcx.sess, span, E0475,
823 "index of slice outside its lifetime");
824 self.tcx.note_and_explain_region(&mut err,
825 "the slice is only valid for ",
830 infer::RelateObjectBound(span) => {
831 let mut err = struct_span_err!(self.tcx.sess, span, E0476,
832 "lifetime of the source pointer does not outlive \
833 lifetime bound of the object type");
834 self.tcx.note_and_explain_region(&mut err,
835 "object type is valid for ",
838 self.tcx.note_and_explain_region(&mut err,
839 "source pointer is only valid for ",
844 infer::RelateParamBound(span, ty) => {
845 let mut err = struct_span_err!(self.tcx.sess, span, E0477,
846 "the type `{}` does not fulfill the required lifetime",
847 self.ty_to_string(ty));
848 self.tcx.note_and_explain_region(&mut err,
849 "type must outlive ",
854 infer::RelateRegionParamBound(span) => {
855 let mut err = struct_span_err!(self.tcx.sess, span, E0478,
856 "lifetime bound not satisfied");
857 self.tcx.note_and_explain_region(&mut err,
858 "lifetime parameter instantiated with ",
861 self.tcx.note_and_explain_region(&mut err,
862 "but lifetime parameter must outlive ",
867 infer::RelateDefaultParamBound(span, ty) => {
868 let mut err = struct_span_err!(self.tcx.sess, span, E0479,
869 "the type `{}` (provided as the value of \
870 a type parameter) is not valid at this point",
871 self.ty_to_string(ty));
872 self.tcx.note_and_explain_region(&mut err,
873 "type must outlive ",
878 infer::CallRcvr(span) => {
879 let mut err = struct_span_err!(self.tcx.sess, span, E0480,
880 "lifetime of method receiver does not outlive \
882 self.tcx.note_and_explain_region(&mut err,
883 "the receiver is only valid for ",
888 infer::CallArg(span) => {
889 let mut err = struct_span_err!(self.tcx.sess, span, E0481,
890 "lifetime of function argument does not outlive \
892 self.tcx.note_and_explain_region(&mut err,
893 "the function argument is only valid for ",
898 infer::CallReturn(span) => {
899 let mut err = struct_span_err!(self.tcx.sess, span, E0482,
900 "lifetime of return value does not outlive \
902 self.tcx.note_and_explain_region(&mut err,
903 "the return value is only valid for ",
908 infer::Operand(span) => {
909 let mut err = struct_span_err!(self.tcx.sess, span, E0483,
910 "lifetime of operand does not outlive \
912 self.tcx.note_and_explain_region(&mut err,
913 "the operand is only valid for ",
918 infer::AddrOf(span) => {
919 let mut err = struct_span_err!(self.tcx.sess, span, E0484,
920 "reference is not valid at the time of borrow");
921 self.tcx.note_and_explain_region(&mut err,
922 "the borrow is only valid for ",
927 infer::AutoBorrow(span) => {
928 let mut err = struct_span_err!(self.tcx.sess, span, E0485,
929 "automatically reference is not valid \
930 at the time of borrow");
931 self.tcx.note_and_explain_region(&mut err,
932 "the automatic borrow is only valid for ",
937 infer::ExprTypeIsNotInScope(t, span) => {
938 let mut err = struct_span_err!(self.tcx.sess, span, E0486,
939 "type of expression contains references \
940 that are not valid during the expression: `{}`",
941 self.ty_to_string(t));
942 self.tcx.note_and_explain_region(&mut err,
943 "type is only valid for ",
948 infer::SafeDestructor(span) => {
949 let mut err = struct_span_err!(self.tcx.sess, span, E0487,
950 "unsafe use of destructor: destructor might be called \
951 while references are dead");
952 // FIXME (22171): terms "super/subregion" are suboptimal
953 self.tcx.note_and_explain_region(&mut err,
957 self.tcx.note_and_explain_region(&mut err,
963 infer::BindingTypeIsNotValidAtDecl(span) => {
964 let mut err = struct_span_err!(self.tcx.sess, span, E0488,
965 "lifetime of variable does not enclose its declaration");
966 self.tcx.note_and_explain_region(&mut err,
967 "the variable is only valid for ",
972 infer::ParameterInScope(_, span) => {
973 let mut err = struct_span_err!(self.tcx.sess, span, E0489,
974 "type/lifetime parameter not in scope here");
975 self.tcx.note_and_explain_region(&mut err,
976 "the parameter is only valid for ",
981 infer::DataBorrowed(ty, span) => {
982 let mut err = struct_span_err!(self.tcx.sess, span, E0490,
983 "a value of type `{}` is borrowed for too long",
984 self.ty_to_string(ty));
985 self.tcx.note_and_explain_region(&mut err, "the type is valid for ", sub, "");
986 self.tcx.note_and_explain_region(&mut err, "but the borrow lasts for ", sup, "");
989 infer::ReferenceOutlivesReferent(ty, span) => {
990 let mut err = struct_span_err!(self.tcx.sess, span, E0491,
991 "in type `{}`, reference has a longer lifetime \
992 than the data it references",
993 self.ty_to_string(ty));
994 self.tcx.note_and_explain_region(&mut err,
995 "the pointer is valid for ",
998 self.tcx.note_and_explain_region(&mut err,
999 "but the referenced data is only valid for ",
1004 infer::CompareImplMethodObligation { span,
1009 self.report_extra_impl_obligation(span,
1013 &format!("`{}: {}`", sup, sub),
1019 fn report_sub_sup_conflict(&self,
1020 var_origin: RegionVariableOrigin,
1021 sub_origin: SubregionOrigin<'tcx>,
1022 sub_region: &'tcx Region,
1023 sup_origin: SubregionOrigin<'tcx>,
1024 sup_region: &'tcx Region) {
1025 let mut err = self.report_inference_failure(var_origin);
1027 self.tcx.note_and_explain_region(&mut err,
1028 "first, the lifetime cannot outlive ",
1032 self.note_region_origin(&mut err, &sup_origin);
1034 self.tcx.note_and_explain_region(&mut err,
1035 "but, the lifetime must be valid for ",
1039 self.note_region_origin(&mut err, &sub_origin);
1043 fn report_processed_errors(&self,
1044 origins: &[ProcessedErrorOrigin<'tcx>]) {
1045 for origin in origins.iter() {
1046 let mut err = match *origin {
1047 ProcessedErrorOrigin::VariableFailure(ref var_origin) =>
1048 self.report_inference_failure(var_origin.clone()),
1049 ProcessedErrorOrigin::ConcreteFailure(ref sr_origin, sub, sup) =>
1050 self.report_concrete_failure(sr_origin.clone(), sub, sup),
1057 pub fn issue_32330_warnings(&self, span: Span, issue32330s: &[ty::Issue32330]) {
1058 for issue32330 in issue32330s {
1060 ty::Issue32330::WontChange => { }
1061 ty::Issue32330::WillChange { fn_def_id, region_name } => {
1062 self.tcx.sess.add_lint(
1063 lint::builtin::HR_LIFETIME_IN_ASSOC_TYPE,
1066 format!("lifetime parameter `{0}` declared on fn `{1}` \
1067 appears only in the return type, \
1068 but here is required to be higher-ranked, \
1069 which means that `{0}` must appear in both \
1070 argument and return types",
1072 self.tcx.item_path_str(fn_def_id)));
1079 impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
1080 fn report_inference_failure(&self,
1081 var_origin: RegionVariableOrigin)
1082 -> DiagnosticBuilder<'tcx> {
1083 let br_string = |br: ty::BoundRegion| {
1084 let mut s = br.to_string();
1090 let var_description = match var_origin {
1091 infer::MiscVariable(_) => "".to_string(),
1092 infer::PatternRegion(_) => " for pattern".to_string(),
1093 infer::AddrOfRegion(_) => " for borrow expression".to_string(),
1094 infer::Autoref(_) => " for autoref".to_string(),
1095 infer::Coercion(_) => " for automatic coercion".to_string(),
1096 infer::LateBoundRegion(_, br, infer::FnCall) => {
1097 format!(" for lifetime parameter {}in function call",
1100 infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
1101 format!(" for lifetime parameter {}in generic type", br_string(br))
1103 infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
1104 format!(" for lifetime parameter {}in trait containing associated type `{}`",
1105 br_string(br), type_name)
1107 infer::EarlyBoundRegion(_, name) => {
1108 format!(" for lifetime parameter `{}`",
1111 infer::BoundRegionInCoherence(name) => {
1112 format!(" for lifetime parameter `{}` in coherence check",
1115 infer::UpvarRegion(ref upvar_id, _) => {
1116 format!(" for capture of `{}` by closure",
1117 self.tcx.local_var_name_str(upvar_id.var_id).to_string())
1121 struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
1122 "cannot infer an appropriate lifetime{} \
1123 due to conflicting requirements",
1127 fn note_region_origin(&self, err: &mut DiagnosticBuilder, origin: &SubregionOrigin<'tcx>) {
1129 infer::Subtype(ref trace) => {
1130 if let Some((expected, found)) = self.values_str(&trace.values) {
1131 // FIXME: do we want a "the" here?
1134 &format!("...so that {} (expected {}, found {})",
1135 trace.cause.as_requirement_str(), expected, found));
1137 // FIXME: this really should be handled at some earlier stage. Our
1138 // handling of region checking when type errors are present is
1143 &format!("...so that {}",
1144 trace.cause.as_requirement_str()));
1147 infer::Reborrow(span) => {
1150 "...so that reference does not outlive \
1153 infer::ReborrowUpvar(span, ref upvar_id) => {
1157 "...so that closure can access `{}`",
1158 self.tcx.local_var_name_str(upvar_id.var_id)
1161 infer::InfStackClosure(span) => {
1164 "...so that closure does not outlive its stack frame");
1166 infer::InvokeClosure(span) => {
1169 "...so that closure is not invoked outside its lifetime");
1171 infer::DerefPointer(span) => {
1174 "...so that pointer is not dereferenced \
1175 outside its lifetime");
1177 infer::FreeVariable(span, id) => {
1180 &format!("...so that captured variable `{}` \
1181 does not outlive the enclosing closure",
1182 self.tcx.local_var_name_str(id)));
1184 infer::IndexSlice(span) => {
1187 "...so that slice is not indexed outside the lifetime");
1189 infer::RelateObjectBound(span) => {
1192 "...so that it can be closed over into an object");
1194 infer::CallRcvr(span) => {
1197 "...so that method receiver is valid for the method call");
1199 infer::CallArg(span) => {
1202 "...so that argument is valid for the call");
1204 infer::CallReturn(span) => {
1207 "...so that return value is valid for the call");
1209 infer::Operand(span) => {
1212 "...so that operand is valid for operation");
1214 infer::AddrOf(span) => {
1217 "...so that reference is valid \
1218 at the time of borrow");
1220 infer::AutoBorrow(span) => {
1223 "...so that auto-reference is valid \
1224 at the time of borrow");
1226 infer::ExprTypeIsNotInScope(t, span) => {
1229 &format!("...so type `{}` of expression is valid during the \
1231 self.ty_to_string(t)));
1233 infer::BindingTypeIsNotValidAtDecl(span) => {
1236 "...so that variable is valid at time of its declaration");
1238 infer::ParameterInScope(_, span) => {
1241 "...so that a type/lifetime parameter is in scope here");
1243 infer::DataBorrowed(ty, span) => {
1246 &format!("...so that the type `{}` is not borrowed for too long",
1247 self.ty_to_string(ty)));
1249 infer::ReferenceOutlivesReferent(ty, span) => {
1252 &format!("...so that the reference type `{}` \
1253 does not outlive the data it points at",
1254 self.ty_to_string(ty)));
1256 infer::RelateParamBound(span, t) => {
1259 &format!("...so that the type `{}` \
1260 will meet its required lifetime bounds",
1261 self.ty_to_string(t)));
1263 infer::RelateDefaultParamBound(span, t) => {
1266 &format!("...so that type parameter \
1267 instantiated with `{}`, \
1268 will meet its declared lifetime bounds",
1269 self.ty_to_string(t)));
1271 infer::RelateRegionParamBound(span) => {
1274 "...so that the declared lifetime parameter bounds \
1277 infer::SafeDestructor(span) => {
1280 "...so that references are valid when the destructor \
1283 infer::CompareImplMethodObligation { span, .. } => {
1286 "...so that the definition in impl matches the definition from the trait");
1292 impl<'tcx> ObligationCause<'tcx> {
1293 fn as_failure_str(&self) -> &'static str {
1294 use traits::ObligationCauseCode::*;
1296 CompareImplMethodObligation { .. } => "method not compatible with trait",
1297 MatchExpressionArm { source, .. } => match source {
1298 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
1299 _ => "match arms have incompatible types",
1301 IfExpression => "if and else have incompatible types",
1302 IfExpressionWithNoElse => "if may be missing an else clause",
1303 EquatePredicate => "equality predicate not satisfied",
1304 MainFunctionType => "main function has wrong type",
1305 StartFunctionType => "start function has wrong type",
1306 IntrinsicType => "intrinsic has wrong type",
1307 MethodReceiver => "mismatched method receiver",
1308 _ => "mismatched types",
1312 fn as_requirement_str(&self) -> &'static str {
1313 use traits::ObligationCauseCode::*;
1315 CompareImplMethodObligation { .. } => "method type is compatible with trait",
1316 ExprAssignable => "expression is assignable",
1317 MatchExpressionArm { source, .. } => match source {
1318 hir::MatchSource::IfLetDesugar{..} => "`if let` arms have compatible types",
1319 _ => "match arms have compatible types",
1321 IfExpression => "if and else have compatible types",
1322 IfExpressionWithNoElse => "if missing an else returns ()",
1323 EquatePredicate => "equality where clause is satisfied",
1324 MainFunctionType => "`main` function has the correct type",
1325 StartFunctionType => "`start` function has the correct type",
1326 IntrinsicType => "intrinsic has the correct type",
1327 MethodReceiver => "method receiver has the correct type",
1328 _ => "types are compatible",