1 // Copyright 2017 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 use borrow_check::nll::constraints::{OutlivesConstraint};
12 use borrow_check::nll::region_infer::RegionInferenceContext;
13 use rustc::hir::def_id::DefId;
14 use rustc::infer::error_reporting::nice_region_error::NiceRegionError;
15 use rustc::infer::InferCtxt;
16 use rustc::mir::{ConstraintCategory, Location, Mir};
17 use rustc::ty::{self, RegionVid};
18 use rustc_data_structures::indexed_vec::IndexVec;
19 use rustc_errors::{Diagnostic, DiagnosticBuilder};
20 use std::collections::VecDeque;
22 use syntax::symbol::keywords;
24 use syntax::errors::Applicability;
29 use self::region_name::RegionName;
31 trait ConstraintDescription {
32 fn description(&self) -> &'static str;
35 impl ConstraintDescription for ConstraintCategory {
36 fn description(&self) -> &'static str {
37 // Must end with a space. Allows for empty names to be provided.
39 ConstraintCategory::Assignment => "assignment ",
40 ConstraintCategory::Return => "returning this value ",
41 ConstraintCategory::Cast => "cast ",
42 ConstraintCategory::CallArgument => "argument ",
43 ConstraintCategory::TypeAnnotation => "type annotation ",
44 ConstraintCategory::ClosureBounds => "closure body ",
45 ConstraintCategory::SizedBound => "proving this value is `Sized` ",
46 ConstraintCategory::CopyBound => "copying this value ",
47 ConstraintCategory::OpaqueType => "opaque type ",
48 ConstraintCategory::Boring
49 | ConstraintCategory::BoringNoLocation
50 | ConstraintCategory::Internal => "",
55 #[derive(Copy, Clone, PartialEq, Eq)]
58 FromOutlivesConstraint(OutlivesConstraint),
62 impl<'tcx> RegionInferenceContext<'tcx> {
63 /// Tries to find the best constraint to blame for the fact that
64 /// `R: from_region`, where `R` is some region that meets
65 /// `target_test`. This works by following the constraint graph,
66 /// creating a constraint path that forces `R` to outlive
67 /// `from_region`, and then finding the best choices within that
69 fn best_blame_constraint(
72 from_region: RegionVid,
73 target_test: impl Fn(RegionVid) -> bool,
74 ) -> (ConstraintCategory, Span, RegionVid) {
75 debug!("best_blame_constraint(from_region={:?})", from_region);
78 let (path, target_region) = self
79 .find_constraint_paths_between_regions(from_region, target_test)
82 "best_blame_constraint: path={:#?}",
87 self.constraint_sccs.scc(c.sup),
88 self.constraint_sccs.scc(c.sub),
93 // Classify each of the constraints along the path.
94 let mut categorized_path: Vec<(ConstraintCategory, Span)> = path
96 .map(|constraint| (constraint.category, constraint.locations.span(mir)))
99 "best_blame_constraint: categorized_path={:#?}",
103 // To find the best span to cite, we first try to look for the
104 // final constraint that is interesting and where the `sup` is
105 // not unified with the ultimate target region. The reason
106 // for this is that we have a chain of constraints that lead
107 // from the source to the target region, something like:
109 // '0: '1 ('0 is the source)
114 // '5: '6 ('6 is the target)
116 // Some of those regions are unified with `'6` (in the same
117 // SCC). We want to screen those out. After that point, the
118 // "closest" constraint we have to the end is going to be the
119 // most likely to be the point where the value escapes -- but
120 // we still want to screen for an "interesting" point to
121 // highlight (e.g., a call site or something).
122 let target_scc = self.constraint_sccs.scc(target_region);
123 let best_choice = (0..path.len()).rev().find(|&i| {
124 let constraint = path[i];
126 let constraint_sup_scc = self.constraint_sccs.scc(constraint.sup);
128 match categorized_path[i].0 {
129 ConstraintCategory::OpaqueType
130 | ConstraintCategory::Boring
131 | ConstraintCategory::BoringNoLocation
132 | ConstraintCategory::Internal => false,
133 _ => constraint_sup_scc != target_scc,
136 if let Some(i) = best_choice {
137 let (category, span) = categorized_path[i];
138 return (category, span, target_region);
141 // If that search fails, that is.. unusual. Maybe everything
142 // is in the same SCC or something. In that case, find what
143 // appears to be the most interesting point to report to the
144 // user via an even more ad-hoc guess.
145 categorized_path.sort_by(|p0, p1| p0.0.cmp(&p1.0));
146 debug!("best_blame_constraint: sorted_path={:#?}", categorized_path);
148 let &(category, span) = categorized_path.first().unwrap();
150 (category, span, target_region)
153 /// Walks the graph of constraints (where `'a: 'b` is considered
154 /// an edge `'a -> 'b`) to find all paths from `from_region` to
155 /// `to_region`. The paths are accumulated into the vector
156 /// `results`. The paths are stored as a series of
157 /// `ConstraintIndex` values -- in other words, a list of *edges*.
159 /// Returns: a series of constraints as well as the region `R`
160 /// that passed the target test.
161 fn find_constraint_paths_between_regions(
163 from_region: RegionVid,
164 target_test: impl Fn(RegionVid) -> bool,
165 ) -> Option<(Vec<OutlivesConstraint>, RegionVid)> {
166 let mut context = IndexVec::from_elem(Trace::NotVisited, &self.definitions);
167 context[from_region] = Trace::StartRegion;
169 // Use a deque so that we do a breadth-first search. We will
170 // stop at the first match, which ought to be the shortest
171 // path (fewest constraints).
172 let mut deque = VecDeque::new();
173 deque.push_back(from_region);
175 while let Some(r) = deque.pop_front() {
176 // Check if we reached the region we were looking for. If so,
177 // we can reconstruct the path that led to it and return it.
179 let mut result = vec![];
183 Trace::NotVisited => {
184 bug!("found unvisited region {:?} on path to {:?}", p, r)
186 Trace::FromOutlivesConstraint(c) => {
191 Trace::StartRegion => {
193 return Some((result, r));
199 // Otherwise, walk over the outgoing constraints and
200 // enqueue any regions we find, keeping track of how we
202 let fr_static = self.universal_regions.fr_static;
203 for constraint in self.constraint_graph.outgoing_edges(r,
206 assert_eq!(constraint.sup, r);
207 let sub_region = constraint.sub;
208 if let Trace::NotVisited = context[sub_region] {
209 context[sub_region] = Trace::FromOutlivesConstraint(constraint);
210 deque.push_back(sub_region);
218 /// Report an error because the universal region `fr` was required to outlive
219 /// `outlived_fr` but it is not known to do so. For example:
222 /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
225 /// Here we would be invoked with `fr = 'a` and `outlived_fr = `'b`.
226 pub(super) fn report_error(
229 infcx: &InferCtxt<'_, '_, 'tcx>,
232 outlived_fr: RegionVid,
233 errors_buffer: &mut Vec<Diagnostic>,
235 debug!("report_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
237 let (category, span, _) = self.best_blame_constraint(
243 // Check if we can use one of the "nice region errors".
244 if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
245 let tables = infcx.tcx.typeck_tables_of(mir_def_id);
246 let nice = NiceRegionError::new_from_span(infcx.tcx, span, o, f, Some(tables));
247 if let Some(_error_reported) = nice.try_report_from_nll() {
252 let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
253 self.universal_regions.is_local_free_region(fr),
254 self.universal_regions.is_local_free_region(outlived_fr),
257 debug!("report_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
258 fr_is_local, outlived_fr_is_local, category);
259 match (category, fr_is_local, outlived_fr_is_local) {
260 (ConstraintCategory::Assignment, true, false) |
261 (ConstraintCategory::CallArgument, true, false) =>
262 self.report_escaping_data_error(mir, infcx, mir_def_id, fr, outlived_fr,
263 category, span, errors_buffer),
265 self.report_general_error(mir, infcx, mir_def_id, fr, fr_is_local,
266 outlived_fr, outlived_fr_is_local,
267 category, span, errors_buffer),
271 fn report_escaping_data_error(
274 infcx: &InferCtxt<'_, '_, 'tcx>,
277 outlived_fr: RegionVid,
278 category: ConstraintCategory,
280 errors_buffer: &mut Vec<Diagnostic>,
282 let fr_name_and_span = self.get_var_name_and_span_for_region(infcx.tcx, mir, fr);
283 let outlived_fr_name_and_span =
284 self.get_var_name_and_span_for_region(infcx.tcx, mir, outlived_fr);
286 let escapes_from = if infcx.tcx.is_closure(mir_def_id) { "closure" } else { "function" };
288 // Revert to the normal error in these cases.
289 // Assignments aren't "escapes" in function items.
290 if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
291 || (category == ConstraintCategory::Assignment && escapes_from == "function")
293 return self.report_general_error(mir, infcx, mir_def_id,
294 fr, true, outlived_fr, false,
295 category, span, errors_buffer);
298 let mut diag = infcx.tcx.sess.struct_span_err(
299 span, &format!("borrowed data escapes outside of {}", escapes_from),
302 if let Some((outlived_fr_name, outlived_fr_span)) = outlived_fr_name_and_span {
303 if let Some(name) = outlived_fr_name {
306 format!("`{}` is declared here, outside of the {} body", name, escapes_from),
311 if let Some((fr_name, fr_span)) = fr_name_and_span {
312 if let Some(name) = fr_name {
315 format!("`{}` is a reference that is only valid in the {} body",
319 diag.span_label(span, format!("`{}` escapes the {} body here",
320 name, escapes_from));
324 diag.buffer(errors_buffer);
327 fn report_general_error(
330 infcx: &InferCtxt<'_, '_, 'tcx>,
334 outlived_fr: RegionVid,
335 outlived_fr_is_local: bool,
336 category: ConstraintCategory,
338 errors_buffer: &mut Vec<Diagnostic>,
340 let mut diag = infcx.tcx.sess.struct_span_err(
342 "unsatisfied lifetime constraints", // FIXME
345 let counter = &mut 1;
346 let fr_name = self.give_region_a_name(infcx, mir, mir_def_id, fr, counter);
347 fr_name.highlight_region_name(&mut diag);
348 let outlived_fr_name = self.give_region_a_name(
349 infcx, mir, mir_def_id, outlived_fr, counter);
350 outlived_fr_name.highlight_region_name(&mut diag);
352 let mir_def_name = if infcx.tcx.is_closure(mir_def_id) { "closure" } else { "function" };
354 match (category, outlived_fr_is_local, fr_is_local) {
355 (ConstraintCategory::Return, true, _) => {
356 diag.span_label(span, format!(
357 "{} was supposed to return data with lifetime `{}` but it is returning \
358 data with lifetime `{}`",
359 mir_def_name, outlived_fr_name, fr_name
363 diag.span_label(span, format!(
364 "{}requires that `{}` must outlive `{}`",
365 category.description(), fr_name, outlived_fr_name,
370 self.add_static_impl_trait_suggestion(
371 infcx, &mut diag, fr, fr_name, outlived_fr,
374 diag.buffer(errors_buffer);
377 fn add_static_impl_trait_suggestion(
379 infcx: &InferCtxt<'_, '_, 'tcx>,
380 diag: &mut DiagnosticBuilder<'_>,
382 // We need to pass `fr_name` - computing it again will label it twice.
384 outlived_fr: RegionVid,
388 Some(ty::RegionKind::ReStatic)
389 ) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
390 if let Some(ty::TyS {
391 sty: ty::TyKind::Opaque(did, substs),
393 }) = infcx.tcx.is_suitable_region(f)
395 .map(|id| infcx.tcx.return_type_impl_trait(id))
398 // Check whether or not the impl trait return type is intended to capture
399 // data with the static lifetime.
401 // eg. check for `impl Trait + 'static` instead of `impl Trait`.
402 let has_static_predicate = {
403 let predicates_of = infcx.tcx.predicates_of(*did);
404 let bounds = predicates_of.instantiate(infcx.tcx, substs);
406 let mut found = false;
407 for predicate in bounds.predicates {
408 if let ty::Predicate::TypeOutlives(binder) = predicate {
409 if let ty::OutlivesPredicate(
411 ty::RegionKind::ReStatic
412 ) = binder.skip_binder() {
422 debug!("add_static_impl_trait_suggestion: has_static_predicate={:?}",
423 has_static_predicate);
424 let static_str = keywords::StaticLifetime.name();
425 // If there is a static predicate, then the only sensible suggestion is to replace
426 // fr with `'static`.
427 if has_static_predicate {
430 "consider replacing `{}` with `{}`",
435 // Otherwise, we should suggest adding a constraint on the return type.
436 let span = infcx.tcx.def_span(*did);
437 if let Ok(snippet) = infcx.tcx.sess.source_map().span_to_snippet(span) {
438 let suggestable_fr_name = if fr_name.was_named() {
439 format!("{}", fr_name)
444 diag.span_suggestion_with_applicability(
447 "to allow this impl Trait to capture borrowed data with lifetime \
448 `{}`, add `{}` as a constraint",
449 fr_name, suggestable_fr_name,
451 format!("{} + {}", snippet, suggestable_fr_name),
452 Applicability::MachineApplicable,
460 // Finds some region R such that `fr1: R` and `R` is live at
462 crate fn find_sub_region_live_at(&self, fr1: RegionVid, elem: Location) -> RegionVid {
465 self.find_constraint_paths_between_regions(fr1, |r| {
466 self.liveness_constraints.contains(r, elem)
471 // Finds a good span to blame for the fact that `fr1` outlives `fr2`.
472 crate fn find_outlives_blame_span(
478 let (_, span, _) = self.best_blame_constraint(mir, fr1, |r| r == fr2);