]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/region_infer/error_reporting/mod.rs
Move ConstraintCategory to rustc::mir
[rust.git] / src / librustc_mir / borrow_check / nll / region_infer / error_reporting / mod.rs
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.
4 //
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.
10
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;
21 use std::fmt;
22 use syntax::symbol::keywords;
23 use syntax_pos::Span;
24 use syntax::errors::Applicability;
25
26 mod region_name;
27 mod var_name;
28
29 use self::region_name::RegionName;
30
31 trait ConstraintDescription {
32     fn description(&self) -> &'static str;
33 }
34
35 impl ConstraintDescription for ConstraintCategory {
36     fn description(&self) -> &'static str {
37         // Must end with a space. Allows for empty names to be provided.
38         match self {
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 => "",
51         }
52     }
53 }
54
55 #[derive(Copy, Clone, PartialEq, Eq)]
56 enum Trace {
57     StartRegion,
58     FromOutlivesConstraint(OutlivesConstraint),
59     NotVisited,
60 }
61
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
68     /// path to blame.
69     fn best_blame_constraint(
70         &self,
71         mir: &Mir<'tcx>,
72         from_region: RegionVid,
73         target_test: impl Fn(RegionVid) -> bool,
74     ) -> (ConstraintCategory, Span, RegionVid) {
75         debug!("best_blame_constraint(from_region={:?})", from_region);
76
77         // Find all paths
78         let (path, target_region) = self
79             .find_constraint_paths_between_regions(from_region, target_test)
80             .unwrap();
81         debug!(
82             "best_blame_constraint: path={:#?}",
83             path.iter()
84                 .map(|&c| format!(
85                     "{:?} ({:?}: {:?})",
86                     c,
87                     self.constraint_sccs.scc(c.sup),
88                     self.constraint_sccs.scc(c.sub),
89                 ))
90                 .collect::<Vec<_>>()
91         );
92
93         // Classify each of the constraints along the path.
94         let mut categorized_path: Vec<(ConstraintCategory, Span)> = path
95             .iter()
96             .map(|constraint| (constraint.category, constraint.locations.span(mir)))
97             .collect();
98         debug!(
99             "best_blame_constraint: categorized_path={:#?}",
100             categorized_path
101         );
102
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:
108         //
109         //    '0: '1 ('0 is the source)
110         //    '1: '2
111         //    '2: '3
112         //    '3: '4
113         //    '4: '5
114         //    '5: '6 ('6 is the target)
115         //
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];
125
126             let constraint_sup_scc = self.constraint_sccs.scc(constraint.sup);
127
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,
134             }
135         });
136         if let Some(i) = best_choice {
137             let (category, span) = categorized_path[i];
138             return (category, span, target_region);
139         }
140
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);
147
148         let &(category, span) = categorized_path.first().unwrap();
149
150         (category, span, target_region)
151     }
152
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*.
158     ///
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(
162         &self,
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;
168
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);
174
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.
178             if target_test(r) {
179                 let mut result = vec![];
180                 let mut p = r;
181                 loop {
182                     match context[p] {
183                         Trace::NotVisited => {
184                             bug!("found unvisited region {:?} on path to {:?}", p, r)
185                         }
186                         Trace::FromOutlivesConstraint(c) => {
187                             result.push(c);
188                             p = c.sup;
189                         }
190
191                         Trace::StartRegion => {
192                             result.reverse();
193                             return Some((result, r));
194                         }
195                     }
196                 }
197             }
198
199             // Otherwise, walk over the outgoing constraints and
200             // enqueue any regions we find, keeping track of how we
201             // reached them.
202             let fr_static = self.universal_regions.fr_static;
203             for constraint in self.constraint_graph.outgoing_edges(r,
204                                                                    &self.constraints,
205                                                                    fr_static) {
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);
211                 }
212             }
213         }
214
215         None
216     }
217
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:
220     ///
221     /// ```
222     /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
223     /// ```
224     ///
225     /// Here we would be invoked with `fr = 'a` and `outlived_fr = `'b`.
226     pub(super) fn report_error(
227         &self,
228         mir: &Mir<'tcx>,
229         infcx: &InferCtxt<'_, '_, 'tcx>,
230         mir_def_id: DefId,
231         fr: RegionVid,
232         outlived_fr: RegionVid,
233         errors_buffer: &mut Vec<Diagnostic>,
234     ) {
235         debug!("report_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
236
237         let (category, span, _) = self.best_blame_constraint(
238             mir,
239             fr,
240             |r| r == outlived_fr
241         );
242
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() {
248                 return;
249             }
250         }
251
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),
255         );
256
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),
264             _ =>
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),
268         };
269     }
270
271     fn report_escaping_data_error(
272         &self,
273         mir: &Mir<'tcx>,
274         infcx: &InferCtxt<'_, '_, 'tcx>,
275         mir_def_id: DefId,
276         fr: RegionVid,
277         outlived_fr: RegionVid,
278         category: ConstraintCategory,
279         span: Span,
280         errors_buffer: &mut Vec<Diagnostic>,
281     ) {
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);
285
286         let escapes_from = if infcx.tcx.is_closure(mir_def_id) { "closure" } else { "function" };
287
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")
292         {
293             return self.report_general_error(mir, infcx, mir_def_id,
294                                              fr, true, outlived_fr, false,
295                                              category, span, errors_buffer);
296         }
297
298         let mut diag = infcx.tcx.sess.struct_span_err(
299             span, &format!("borrowed data escapes outside of {}", escapes_from),
300         );
301
302         if let Some((outlived_fr_name, outlived_fr_span)) = outlived_fr_name_and_span {
303             if let Some(name) = outlived_fr_name {
304                 diag.span_label(
305                     outlived_fr_span,
306                     format!("`{}` is declared here, outside of the {} body", name, escapes_from),
307                 );
308             }
309         }
310
311         if let Some((fr_name, fr_span)) = fr_name_and_span {
312             if let Some(name) = fr_name {
313                 diag.span_label(
314                     fr_span,
315                     format!("`{}` is a reference that is only valid in the {} body",
316                             name, escapes_from),
317                 );
318
319                 diag.span_label(span, format!("`{}` escapes the {} body here",
320                                                name, escapes_from));
321             }
322         }
323
324         diag.buffer(errors_buffer);
325     }
326
327     fn report_general_error(
328         &self,
329         mir: &Mir<'tcx>,
330         infcx: &InferCtxt<'_, '_, 'tcx>,
331         mir_def_id: DefId,
332         fr: RegionVid,
333         fr_is_local: bool,
334         outlived_fr: RegionVid,
335         outlived_fr_is_local: bool,
336         category: ConstraintCategory,
337         span: Span,
338         errors_buffer: &mut Vec<Diagnostic>,
339     ) {
340         let mut diag = infcx.tcx.sess.struct_span_err(
341             span,
342             "unsatisfied lifetime constraints", // FIXME
343         );
344
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);
351
352         let mir_def_name = if infcx.tcx.is_closure(mir_def_id) { "closure" } else { "function" };
353
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
360                 ));
361             },
362             _ => {
363                 diag.span_label(span, format!(
364                     "{}requires that `{}` must outlive `{}`",
365                     category.description(), fr_name, outlived_fr_name,
366                 ));
367             },
368         }
369
370         self.add_static_impl_trait_suggestion(
371             infcx, &mut diag, fr, fr_name, outlived_fr,
372         );
373
374         diag.buffer(errors_buffer);
375     }
376
377     fn add_static_impl_trait_suggestion(
378         &self,
379         infcx: &InferCtxt<'_, '_, 'tcx>,
380         diag: &mut DiagnosticBuilder<'_>,
381         fr: RegionVid,
382         // We need to pass `fr_name` - computing it again will label it twice.
383         fr_name: RegionName,
384         outlived_fr: RegionVid,
385     ) {
386         if let (
387             Some(f),
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),
392                 ..
393             }) = infcx.tcx.is_suitable_region(f)
394                     .map(|r| r.def_id)
395                     .map(|id| infcx.tcx.return_type_impl_trait(id))
396                     .unwrap_or(None)
397             {
398                 // Check whether or not the impl trait return type is intended to capture
399                 // data with the static lifetime.
400                 //
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);
405
406                     let mut found = false;
407                     for predicate in bounds.predicates {
408                         if let ty::Predicate::TypeOutlives(binder) = predicate {
409                             if let ty::OutlivesPredicate(
410                                 _,
411                                 ty::RegionKind::ReStatic
412                             ) = binder.skip_binder() {
413                                 found = true;
414                                 break;
415                             }
416                         }
417                     }
418
419                     found
420                 };
421
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 {
428                     diag.help(
429                         &format!(
430                             "consider replacing `{}` with `{}`",
431                             fr_name, static_str,
432                         ),
433                     );
434                 } else {
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)
440                         } else {
441                             "'_".to_string()
442                         };
443
444                         diag.span_suggestion_with_applicability(
445                             span,
446                             &format!(
447                                 "to allow this impl Trait to capture borrowed data with lifetime \
448                                  `{}`, add `{}` as a constraint",
449                                 fr_name, suggestable_fr_name,
450                             ),
451                             format!("{} + {}", snippet, suggestable_fr_name),
452                             Applicability::MachineApplicable,
453                         );
454                     }
455                 }
456             }
457         }
458     }
459
460     // Finds some region R such that `fr1: R` and `R` is live at
461     // `elem`.
462     crate fn find_sub_region_live_at(&self, fr1: RegionVid, elem: Location) -> RegionVid {
463         // Find all paths
464         let (_path, r) =
465             self.find_constraint_paths_between_regions(fr1, |r| {
466                 self.liveness_constraints.contains(r, elem)
467             }).unwrap();
468         r
469     }
470
471     // Finds a good span to blame for the fact that `fr1` outlives `fr2`.
472     crate fn find_outlives_blame_span(
473         &self,
474         mir: &Mir<'tcx>,
475         fr1: RegionVid,
476         fr2: RegionVid,
477     ) -> Span {
478         let (_, span, _) = self.best_blame_constraint(mir, fr1, |r| r == fr2);
479         span
480     }
481 }