]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/diagnostics/region_errors.rs
Remove dead ScopeTree code
[rust.git] / src / librustc_mir / borrow_check / diagnostics / region_errors.rs
1 //! Error reporting machinery for lifetime errors.
2
3 use rustc_errors::{Applicability, DiagnosticBuilder};
4 use rustc_infer::infer::{
5     error_reporting::nice_region_error::NiceRegionError,
6     error_reporting::unexpected_hidden_region_diagnostic, NLLRegionVariableOrigin,
7 };
8 use rustc_middle::mir::ConstraintCategory;
9 use rustc_middle::ty::{self, RegionVid, Ty};
10 use rustc_span::symbol::kw;
11 use rustc_span::Span;
12
13 use crate::util::borrowck_errors;
14
15 use crate::borrow_check::{
16     nll::ConstraintDescription,
17     region_infer::{values::RegionElement, TypeTest},
18     universal_regions::DefiningTy,
19     MirBorrowckCtxt,
20 };
21
22 use super::{OutlivesSuggestionBuilder, RegionName, RegionNameSource};
23
24 impl ConstraintDescription for ConstraintCategory {
25     fn description(&self) -> &'static str {
26         // Must end with a space. Allows for empty names to be provided.
27         match self {
28             ConstraintCategory::Assignment => "assignment ",
29             ConstraintCategory::Return => "returning this value ",
30             ConstraintCategory::Yield => "yielding this value ",
31             ConstraintCategory::UseAsConst => "using this value as a constant ",
32             ConstraintCategory::UseAsStatic => "using this value as a static ",
33             ConstraintCategory::Cast => "cast ",
34             ConstraintCategory::CallArgument => "argument ",
35             ConstraintCategory::TypeAnnotation => "type annotation ",
36             ConstraintCategory::ClosureBounds => "closure body ",
37             ConstraintCategory::SizedBound => "proving this value is `Sized` ",
38             ConstraintCategory::CopyBound => "copying this value ",
39             ConstraintCategory::OpaqueType => "opaque type ",
40             ConstraintCategory::Boring
41             | ConstraintCategory::BoringNoLocation
42             | ConstraintCategory::Internal => "",
43         }
44     }
45 }
46
47 /// A collection of errors encountered during region inference. This is needed to efficiently
48 /// report errors after borrow checking.
49 ///
50 /// Usually we expect this to either be empty or contain a small number of items, so we can avoid
51 /// allocation most of the time.
52 crate type RegionErrors<'tcx> = Vec<RegionErrorKind<'tcx>>;
53
54 #[derive(Clone, Debug)]
55 crate enum RegionErrorKind<'tcx> {
56     /// A generic bound failure for a type test (`T: 'a`).
57     TypeTestError { type_test: TypeTest<'tcx> },
58
59     /// An unexpected hidden region for an opaque type.
60     UnexpectedHiddenRegion {
61         /// The span for the member constraint.
62         span: Span,
63         /// The hidden type.
64         hidden_ty: Ty<'tcx>,
65         /// The unexpected region.
66         member_region: ty::Region<'tcx>,
67     },
68
69     /// Higher-ranked subtyping error.
70     BoundUniversalRegionError {
71         /// The placeholder free region.
72         longer_fr: RegionVid,
73         /// The region element that erroneously must be outlived by `longer_fr`.
74         error_element: RegionElement,
75         /// The origin of the placeholder region.
76         fr_origin: NLLRegionVariableOrigin,
77     },
78
79     /// Any other lifetime error.
80     RegionError {
81         /// The origin of the region.
82         fr_origin: NLLRegionVariableOrigin,
83         /// The region that should outlive `shorter_fr`.
84         longer_fr: RegionVid,
85         /// The region that should be shorter, but we can't prove it.
86         shorter_fr: RegionVid,
87         /// Indicates whether this is a reported error. We currently only report the first error
88         /// encountered and leave the rest unreported so as not to overwhelm the user.
89         is_reported: bool,
90     },
91 }
92
93 /// Information about the various region constraints involved in a borrow checker error.
94 #[derive(Clone, Debug)]
95 pub struct ErrorConstraintInfo {
96     // fr: outlived_fr
97     pub(super) fr: RegionVid,
98     pub(super) fr_is_local: bool,
99     pub(super) outlived_fr: RegionVid,
100     pub(super) outlived_fr_is_local: bool,
101
102     // Category and span for best blame constraint
103     pub(super) category: ConstraintCategory,
104     pub(super) span: Span,
105 }
106
107 impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
108     /// Converts a region inference variable into a `ty::Region` that
109     /// we can use for error reporting. If `r` is universally bound,
110     /// then we use the name that we have on record for it. If `r` is
111     /// existentially bound, then we check its inferred value and try
112     /// to find a good name from that. Returns `None` if we can't find
113     /// one (e.g., this is just some random part of the CFG).
114     pub(super) fn to_error_region(&self, r: RegionVid) -> Option<ty::Region<'tcx>> {
115         self.to_error_region_vid(r).and_then(|r| self.regioncx.region_definition(r).external_name)
116     }
117
118     /// Returns the `RegionVid` corresponding to the region returned by
119     /// `to_error_region`.
120     pub(super) fn to_error_region_vid(&self, r: RegionVid) -> Option<RegionVid> {
121         if self.regioncx.universal_regions().is_universal_region(r) {
122             Some(r)
123         } else {
124             let upper_bound = self.regioncx.universal_upper_bound(r);
125
126             if self.regioncx.upper_bound_in_region_scc(r, upper_bound) {
127                 self.to_error_region_vid(upper_bound)
128             } else {
129                 None
130             }
131         }
132     }
133
134     /// Returns `true` if a closure is inferred to be an `FnMut` closure.
135     fn is_closure_fn_mut(&self, fr: RegionVid) -> bool {
136         if let Some(ty::ReFree(free_region)) = self.to_error_region(fr) {
137             if let ty::BoundRegion::BrEnv = free_region.bound_region {
138                 if let DefiningTy::Closure(_, substs) =
139                     self.regioncx.universal_regions().defining_ty
140                 {
141                     return substs.as_closure().kind() == ty::ClosureKind::FnMut;
142                 }
143             }
144         }
145
146         false
147     }
148
149     /// Produces nice borrowck error diagnostics for all the errors collected in `nll_errors`.
150     pub(in crate::borrow_check) fn report_region_errors(&mut self, nll_errors: RegionErrors<'tcx>) {
151         // Iterate through all the errors, producing a diagnostic for each one. The diagnostics are
152         // buffered in the `MirBorrowckCtxt`.
153
154         let mut outlives_suggestion = OutlivesSuggestionBuilder::default();
155
156         for nll_error in nll_errors.into_iter() {
157             match nll_error {
158                 RegionErrorKind::TypeTestError { type_test } => {
159                     // Try to convert the lower-bound region into something named we can print for the user.
160                     let lower_bound_region = self.to_error_region(type_test.lower_bound);
161
162                     let type_test_span = type_test.locations.span(&self.body);
163
164                     if let Some(lower_bound_region) = lower_bound_region {
165                         self.infcx
166                             .construct_generic_bound_failure(
167                                 type_test_span,
168                                 None,
169                                 type_test.generic_kind,
170                                 lower_bound_region,
171                             )
172                             .buffer(&mut self.errors_buffer);
173                     } else {
174                         // FIXME. We should handle this case better. It
175                         // indicates that we have e.g., some region variable
176                         // whose value is like `'a+'b` where `'a` and `'b` are
177                         // distinct unrelated univesal regions that are not
178                         // known to outlive one another. It'd be nice to have
179                         // some examples where this arises to decide how best
180                         // to report it; we could probably handle it by
181                         // iterating over the universal regions and reporting
182                         // an error that multiple bounds are required.
183                         self.infcx
184                             .tcx
185                             .sess
186                             .struct_span_err(
187                                 type_test_span,
188                                 &format!("`{}` does not live long enough", type_test.generic_kind),
189                             )
190                             .buffer(&mut self.errors_buffer);
191                     }
192                 }
193
194                 RegionErrorKind::UnexpectedHiddenRegion { span, hidden_ty, member_region } => {
195                     let named_ty = self.regioncx.name_regions(self.infcx.tcx, hidden_ty);
196                     let named_region = self.regioncx.name_regions(self.infcx.tcx, member_region);
197                     unexpected_hidden_region_diagnostic(
198                         self.infcx.tcx,
199                         span,
200                         named_ty,
201                         named_region,
202                     )
203                     .buffer(&mut self.errors_buffer);
204                 }
205
206                 RegionErrorKind::BoundUniversalRegionError {
207                     longer_fr,
208                     fr_origin,
209                     error_element,
210                 } => {
211                     let error_region = self.regioncx.region_from_element(longer_fr, error_element);
212
213                     // Find the code to blame for the fact that `longer_fr` outlives `error_fr`.
214                     let (_, span) = self.regioncx.find_outlives_blame_span(
215                         &self.body,
216                         longer_fr,
217                         fr_origin,
218                         error_region,
219                     );
220
221                     // FIXME: improve this error message
222                     self.infcx
223                         .tcx
224                         .sess
225                         .struct_span_err(span, "higher-ranked subtype error")
226                         .buffer(&mut self.errors_buffer);
227                 }
228
229                 RegionErrorKind::RegionError { fr_origin, longer_fr, shorter_fr, is_reported } => {
230                     if is_reported {
231                         self.report_region_error(
232                             longer_fr,
233                             fr_origin,
234                             shorter_fr,
235                             &mut outlives_suggestion,
236                         );
237                     } else {
238                         // We only report the first error, so as not to overwhelm the user. See
239                         // `RegRegionErrorKind` docs.
240                         //
241                         // FIXME: currently we do nothing with these, but perhaps we can do better?
242                         // FIXME: try collecting these constraints on the outlives suggestion
243                         // builder. Does it make the suggestions any better?
244                         debug!(
245                             "Unreported region error: can't prove that {:?}: {:?}",
246                             longer_fr, shorter_fr
247                         );
248                     }
249                 }
250             }
251         }
252
253         // Emit one outlives suggestions for each MIR def we borrowck
254         outlives_suggestion.add_suggestion(self);
255     }
256
257     /// Report an error because the universal region `fr` was required to outlive
258     /// `outlived_fr` but it is not known to do so. For example:
259     ///
260     /// ```
261     /// fn foo<'a, 'b>(x: &'a u32) -> &'b u32 { x }
262     /// ```
263     ///
264     /// Here we would be invoked with `fr = 'a` and `outlived_fr = `'b`.
265     pub(in crate::borrow_check) fn report_region_error(
266         &mut self,
267         fr: RegionVid,
268         fr_origin: NLLRegionVariableOrigin,
269         outlived_fr: RegionVid,
270         outlives_suggestion: &mut OutlivesSuggestionBuilder,
271     ) {
272         debug!("report_region_error(fr={:?}, outlived_fr={:?})", fr, outlived_fr);
273
274         let (category, _, span) =
275             self.regioncx.best_blame_constraint(&self.body, fr, fr_origin, |r| {
276                 self.regioncx.provides_universal_region(r, fr, outlived_fr)
277             });
278
279         debug!("report_region_error: category={:?} {:?}", category, span);
280         // Check if we can use one of the "nice region errors".
281         if let (Some(f), Some(o)) = (self.to_error_region(fr), self.to_error_region(outlived_fr)) {
282             let nice = NiceRegionError::new_from_span(self.infcx, span, o, f);
283             if let Some(diag) = nice.try_report_from_nll() {
284                 diag.buffer(&mut self.errors_buffer);
285                 return;
286             }
287         }
288
289         let (fr_is_local, outlived_fr_is_local): (bool, bool) = (
290             self.regioncx.universal_regions().is_local_free_region(fr),
291             self.regioncx.universal_regions().is_local_free_region(outlived_fr),
292         );
293
294         debug!(
295             "report_region_error: fr_is_local={:?} outlived_fr_is_local={:?} category={:?}",
296             fr_is_local, outlived_fr_is_local, category
297         );
298
299         let errci = ErrorConstraintInfo {
300             fr,
301             outlived_fr,
302             fr_is_local,
303             outlived_fr_is_local,
304             category,
305             span,
306         };
307
308         let diag = match (category, fr_is_local, outlived_fr_is_local) {
309             (ConstraintCategory::Return, true, false) if self.is_closure_fn_mut(fr) => {
310                 self.report_fnmut_error(&errci)
311             }
312             (ConstraintCategory::Assignment, true, false)
313             | (ConstraintCategory::CallArgument, true, false) => {
314                 let mut db = self.report_escaping_data_error(&errci);
315
316                 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
317                 outlives_suggestion.collect_constraint(fr, outlived_fr);
318
319                 db
320             }
321             _ => {
322                 let mut db = self.report_general_error(&errci);
323
324                 outlives_suggestion.intermediate_suggestion(self, &errci, &mut db);
325                 outlives_suggestion.collect_constraint(fr, outlived_fr);
326
327                 db
328             }
329         };
330
331         diag.buffer(&mut self.errors_buffer);
332     }
333
334     /// Report a specialized error when `FnMut` closures return a reference to a captured variable.
335     /// This function expects `fr` to be local and `outlived_fr` to not be local.
336     ///
337     /// ```text
338     /// error: captured variable cannot escape `FnMut` closure body
339     ///   --> $DIR/issue-53040.rs:15:8
340     ///    |
341     /// LL |     || &mut v;
342     ///    |     -- ^^^^^^ creates a reference to a captured variable which escapes the closure body
343     ///    |     |
344     ///    |     inferred to be a `FnMut` closure
345     ///    |
346     ///    = note: `FnMut` closures only have access to their captured variables while they are
347     ///            executing...
348     ///    = note: ...therefore, returned references to captured variables will escape the closure
349     /// ```
350     fn report_fnmut_error(&self, errci: &ErrorConstraintInfo) -> DiagnosticBuilder<'tcx> {
351         let ErrorConstraintInfo { outlived_fr, span, .. } = errci;
352
353         let mut diag = self
354             .infcx
355             .tcx
356             .sess
357             .struct_span_err(*span, "captured variable cannot escape `FnMut` closure body");
358
359         // We should check if the return type of this closure is in fact a closure - in that
360         // case, we can special case the error further.
361         let return_type_is_closure =
362             self.regioncx.universal_regions().unnormalized_output_ty.is_closure();
363         let message = if return_type_is_closure {
364             "returns a closure that contains a reference to a captured variable, which then \
365              escapes the closure body"
366         } else {
367             "returns a reference to a captured variable which escapes the closure body"
368         };
369
370         diag.span_label(*span, message);
371
372         match self.give_region_a_name(*outlived_fr).unwrap().source {
373             RegionNameSource::NamedEarlyBoundRegion(fr_span)
374             | RegionNameSource::NamedFreeRegion(fr_span)
375             | RegionNameSource::SynthesizedFreeEnvRegion(fr_span, _)
376             | RegionNameSource::CannotMatchHirTy(fr_span, _)
377             | RegionNameSource::MatchedHirTy(fr_span)
378             | RegionNameSource::MatchedAdtAndSegment(fr_span)
379             | RegionNameSource::AnonRegionFromUpvar(fr_span, _)
380             | RegionNameSource::AnonRegionFromOutput(fr_span, _, _) => {
381                 diag.span_label(fr_span, "inferred to be a `FnMut` closure");
382             }
383             _ => {}
384         }
385
386         diag.note(
387             "`FnMut` closures only have access to their captured variables while they are \
388              executing...",
389         );
390         diag.note("...therefore, they cannot allow references to captured variables to escape");
391
392         diag
393     }
394
395     /// Reports a error specifically for when data is escaping a closure.
396     ///
397     /// ```text
398     /// error: borrowed data escapes outside of function
399     ///   --> $DIR/lifetime-bound-will-change-warning.rs:44:5
400     ///    |
401     /// LL | fn test2<'a>(x: &'a Box<Fn()+'a>) {
402     ///    |              - `x` is a reference that is only valid in the function body
403     /// LL |     // but ref_obj will not, so warn.
404     /// LL |     ref_obj(x)
405     ///    |     ^^^^^^^^^^ `x` escapes the function body here
406     /// ```
407     fn report_escaping_data_error(&self, errci: &ErrorConstraintInfo) -> DiagnosticBuilder<'tcx> {
408         let ErrorConstraintInfo { span, category, .. } = errci;
409
410         let fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
411             self.infcx.tcx,
412             &self.body,
413             &self.local_names,
414             &self.upvars,
415             errci.fr,
416         );
417         let outlived_fr_name_and_span = self.regioncx.get_var_name_and_span_for_region(
418             self.infcx.tcx,
419             &self.body,
420             &self.local_names,
421             &self.upvars,
422             errci.outlived_fr,
423         );
424
425         let (_, escapes_from) = self
426             .infcx
427             .tcx
428             .article_and_description(self.regioncx.universal_regions().defining_ty.def_id());
429
430         // Revert to the normal error in these cases.
431         // Assignments aren't "escapes" in function items.
432         if (fr_name_and_span.is_none() && outlived_fr_name_and_span.is_none())
433             || (*category == ConstraintCategory::Assignment
434                 && self.regioncx.universal_regions().defining_ty.is_fn_def())
435             || self.regioncx.universal_regions().defining_ty.is_const()
436         {
437             return self.report_general_error(&ErrorConstraintInfo {
438                 fr_is_local: true,
439                 outlived_fr_is_local: false,
440                 ..*errci
441             });
442         }
443
444         let mut diag =
445             borrowck_errors::borrowed_data_escapes_closure(self.infcx.tcx, *span, escapes_from);
446
447         if let Some((Some(outlived_fr_name), outlived_fr_span)) = outlived_fr_name_and_span {
448             diag.span_label(
449                 outlived_fr_span,
450                 format!(
451                     "`{}` declared here, outside of the {} body",
452                     outlived_fr_name, escapes_from
453                 ),
454             );
455         }
456
457         if let Some((Some(fr_name), fr_span)) = fr_name_and_span {
458             diag.span_label(
459                 fr_span,
460                 format!(
461                     "`{}` is a reference that is only valid in the {} body",
462                     fr_name, escapes_from
463                 ),
464             );
465
466             diag.span_label(*span, format!("`{}` escapes the {} body here", fr_name, escapes_from));
467         }
468
469         diag
470     }
471
472     /// Reports a region inference error for the general case with named/synthesized lifetimes to
473     /// explain what is happening.
474     ///
475     /// ```text
476     /// error: unsatisfied lifetime constraints
477     ///   --> $DIR/regions-creating-enums3.rs:17:5
478     ///    |
479     /// LL | fn mk_add_bad1<'a,'b>(x: &'a ast<'a>, y: &'b ast<'b>) -> ast<'a> {
480     ///    |                -- -- lifetime `'b` defined here
481     ///    |                |
482     ///    |                lifetime `'a` defined here
483     /// LL |     ast::add(x, y)
484     ///    |     ^^^^^^^^^^^^^^ function was supposed to return data with lifetime `'a` but it
485     ///    |                    is returning data with lifetime `'b`
486     /// ```
487     fn report_general_error(&self, errci: &ErrorConstraintInfo) -> DiagnosticBuilder<'tcx> {
488         let ErrorConstraintInfo {
489             fr,
490             fr_is_local,
491             outlived_fr,
492             outlived_fr_is_local,
493             span,
494             category,
495             ..
496         } = errci;
497
498         let mut diag =
499             self.infcx.tcx.sess.struct_span_err(*span, "lifetime may not live long enough");
500
501         let (_, mir_def_name) = self.infcx.tcx.article_and_description(self.mir_def_id);
502
503         let fr_name = self.give_region_a_name(*fr).unwrap();
504         fr_name.highlight_region_name(&mut diag);
505         let outlived_fr_name = self.give_region_a_name(*outlived_fr).unwrap();
506         outlived_fr_name.highlight_region_name(&mut diag);
507
508         match (category, outlived_fr_is_local, fr_is_local) {
509             (ConstraintCategory::Return, true, _) => {
510                 diag.span_label(
511                     *span,
512                     format!(
513                         "{} was supposed to return data with lifetime `{}` but it is returning \
514                          data with lifetime `{}`",
515                         mir_def_name, outlived_fr_name, fr_name
516                     ),
517                 );
518             }
519             _ => {
520                 diag.span_label(
521                     *span,
522                     format!(
523                         "{}requires that `{}` must outlive `{}`",
524                         category.description(),
525                         fr_name,
526                         outlived_fr_name,
527                     ),
528                 );
529             }
530         }
531
532         self.add_static_impl_trait_suggestion(&mut diag, *fr, fr_name, *outlived_fr);
533
534         diag
535     }
536
537     /// Adds a suggestion to errors where a `impl Trait` is returned.
538     ///
539     /// ```text
540     /// help: to allow this `impl Trait` to capture borrowed data with lifetime `'1`, add `'_` as
541     ///       a constraint
542     ///    |
543     /// LL |     fn iter_values_anon(&self) -> impl Iterator<Item=u32> + 'a {
544     ///    |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
545     /// ```
546     fn add_static_impl_trait_suggestion(
547         &self,
548         diag: &mut DiagnosticBuilder<'tcx>,
549         fr: RegionVid,
550         // We need to pass `fr_name` - computing it again will label it twice.
551         fr_name: RegionName,
552         outlived_fr: RegionVid,
553     ) {
554         if let (Some(f), Some(ty::RegionKind::ReStatic)) =
555             (self.to_error_region(fr), self.to_error_region(outlived_fr))
556         {
557             if let Some((ty::TyS { kind: ty::Opaque(did, substs), .. }, _)) = self
558                 .infcx
559                 .tcx
560                 .is_suitable_region(f)
561                 .map(|r| r.def_id)
562                 .map(|id| self.infcx.tcx.return_type_impl_trait(id))
563                 .unwrap_or(None)
564             {
565                 // Check whether or not the impl trait return type is intended to capture
566                 // data with the static lifetime.
567                 //
568                 // eg. check for `impl Trait + 'static` instead of `impl Trait`.
569                 let has_static_predicate = {
570                     let predicates_of = self.infcx.tcx.predicates_of(*did);
571                     let bounds = predicates_of.instantiate(self.infcx.tcx, substs);
572
573                     let mut found = false;
574                     for predicate in bounds.predicates {
575                         if let ty::PredicateKind::TypeOutlives(binder) = predicate.kind() {
576                             if let ty::OutlivesPredicate(_, ty::RegionKind::ReStatic) =
577                                 binder.skip_binder()
578                             {
579                                 found = true;
580                                 break;
581                             } else {
582                                 // If there's already a lifetime bound, don't
583                                 // suggest anything.
584                                 return;
585                             }
586                         }
587                     }
588
589                     found
590                 };
591
592                 debug!(
593                     "add_static_impl_trait_suggestion: has_static_predicate={:?}",
594                     has_static_predicate
595                 );
596                 let static_str = kw::StaticLifetime;
597                 // If there is a static predicate, then the only sensible suggestion is to replace
598                 // fr with `'static`.
599                 if has_static_predicate {
600                     diag.help(&format!("consider replacing `{}` with `{}`", fr_name, static_str));
601                 } else {
602                     // Otherwise, we should suggest adding a constraint on the return type.
603                     let span = self.infcx.tcx.def_span(*did);
604                     if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) {
605                         let suggestable_fr_name = if fr_name.was_named() {
606                             fr_name.to_string()
607                         } else {
608                             "'_".to_string()
609                         };
610                         let suggestion = if snippet.ends_with(';') {
611                             // `type X = impl Trait;`
612                             format!("{} + {};", &snippet[..snippet.len() - 1], suggestable_fr_name)
613                         } else {
614                             format!("{} + {}", snippet, suggestable_fr_name)
615                         };
616                         diag.span_suggestion(
617                             span,
618                             &format!(
619                                 "to allow this `impl Trait` to capture borrowed data with lifetime \
620                                  `{}`, add `{}` as a bound",
621                                 fr_name, suggestable_fr_name,
622                             ),
623                             suggestion,
624                             Applicability::MachineApplicable,
625                         );
626                     }
627                 }
628             }
629         }
630     }
631 }