]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs
Auto merge of #60763 - matklad:tt-parser, r=petrochenkov
[rust.git] / src / librustc_mir / borrow_check / nll / region_infer / error_reporting / region_name.rs
1 use std::fmt::{self, Display};
2 use crate::borrow_check::nll::region_infer::RegionInferenceContext;
3 use crate::borrow_check::nll::universal_regions::DefiningTy;
4 use crate::borrow_check::nll::ToRegionVid;
5 use crate::borrow_check::Upvar;
6 use rustc::hir;
7 use rustc::hir::def::{Res, DefKind};
8 use rustc::hir::def_id::DefId;
9 use rustc::infer::InferCtxt;
10 use rustc::mir::Mir;
11 use rustc::ty::subst::{SubstsRef, UnpackedKind};
12 use rustc::ty::{self, RegionKind, RegionVid, Ty, TyCtxt};
13 use rustc::ty::print::RegionHighlightMode;
14 use rustc_errors::DiagnosticBuilder;
15 use syntax::ast::Name;
16 use syntax::symbol::keywords;
17 use syntax_pos::Span;
18 use syntax_pos::symbol::InternedString;
19
20 #[derive(Debug)]
21 crate struct RegionName {
22     crate name: InternedString,
23     crate source: RegionNameSource,
24 }
25
26 #[derive(Debug)]
27 crate enum RegionNameSource {
28     NamedEarlyBoundRegion(Span),
29     NamedFreeRegion(Span),
30     Static,
31     SynthesizedFreeEnvRegion(Span, String),
32     CannotMatchHirTy(Span, String),
33     MatchedHirTy(Span),
34     MatchedAdtAndSegment(Span),
35     AnonRegionFromUpvar(Span, String),
36     AnonRegionFromOutput(Span, String, String),
37     AnonRegionFromYieldTy(Span, String),
38 }
39
40 impl RegionName {
41     #[allow(dead_code)]
42     crate fn was_named(&self) -> bool {
43         match self.source {
44             RegionNameSource::NamedEarlyBoundRegion(..) |
45             RegionNameSource::NamedFreeRegion(..) |
46             RegionNameSource::Static => true,
47             RegionNameSource::SynthesizedFreeEnvRegion(..) |
48             RegionNameSource::CannotMatchHirTy(..) |
49             RegionNameSource::MatchedHirTy(..) |
50             RegionNameSource::MatchedAdtAndSegment(..) |
51             RegionNameSource::AnonRegionFromUpvar(..) |
52             RegionNameSource::AnonRegionFromOutput(..) |
53             RegionNameSource::AnonRegionFromYieldTy(..) => false,
54         }
55     }
56
57     #[allow(dead_code)]
58     crate fn was_synthesized(&self) -> bool {
59         !self.was_named()
60     }
61
62     #[allow(dead_code)]
63     crate fn name(&self) -> &InternedString {
64         &self.name
65     }
66
67     crate fn highlight_region_name(
68         &self,
69         diag: &mut DiagnosticBuilder<'_>
70     ) {
71         match &self.source {
72             RegionNameSource::NamedFreeRegion(span) |
73             RegionNameSource::NamedEarlyBoundRegion(span) => {
74                 diag.span_label(
75                     *span,
76                     format!("lifetime `{}` defined here", self),
77                 );
78             },
79             RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
80                 diag.span_label(
81                     *span,
82                     format!("lifetime `{}` represents this closure's body", self),
83                 );
84                 diag.note(&note);
85             },
86             RegionNameSource::CannotMatchHirTy(span, type_name) => {
87                 diag.span_label(*span, format!("has type `{}`", type_name));
88             },
89             RegionNameSource::MatchedHirTy(span) => {
90                 diag.span_label(
91                     *span,
92                     format!("let's call the lifetime of this reference `{}`", self),
93                 );
94             },
95             RegionNameSource::MatchedAdtAndSegment(span) => {
96                 diag.span_label(*span, format!("let's call this `{}`", self));
97             },
98             RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
99                 diag.span_label(
100                     *span,
101                     format!("lifetime `{}` appears in the type of `{}`", self, upvar_name),
102                 );
103             },
104             RegionNameSource::AnonRegionFromOutput(span, mir_description, type_name) => {
105                 diag.span_label(
106                     *span,
107                     format!("return type{} is {}", mir_description, type_name),
108                 );
109             },
110             RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
111                 diag.span_label(
112                     *span,
113                     format!("yield type is {}", type_name),
114                 );
115             }
116             RegionNameSource::Static => {},
117         }
118     }
119 }
120
121 impl Display for RegionName {
122     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123         write!(f, "{}", self.name)
124     }
125 }
126
127 impl<'tcx> RegionInferenceContext<'tcx> {
128     /// Maps from an internal MIR region vid to something that we can
129     /// report to the user. In some cases, the region vids will map
130     /// directly to lifetimes that the user has a name for (e.g.,
131     /// `'static`). But frequently they will not, in which case we
132     /// have to find some way to identify the lifetime to the user. To
133     /// that end, this function takes a "diagnostic" so that it can
134     /// create auxiliary notes as needed.
135     ///
136     /// Example (function arguments):
137     ///
138     /// Suppose we are trying to give a name to the lifetime of the
139     /// reference `x`:
140     ///
141     /// ```
142     /// fn foo(x: &u32) { .. }
143     /// ```
144     ///
145     /// This function would create a label like this:
146     ///
147     /// ```
148     ///  | fn foo(x: &u32) { .. }
149     ///           ------- fully elaborated type of `x` is `&'1 u32`
150     /// ```
151     ///
152     /// and then return the name `'1` for us to use.
153     crate fn give_region_a_name(
154         &self,
155         infcx: &InferCtxt<'_, '_, 'tcx>,
156         mir: &Mir<'tcx>,
157         upvars: &[Upvar],
158         mir_def_id: DefId,
159         fr: RegionVid,
160         counter: &mut usize,
161     ) -> Option<RegionName> {
162         debug!("give_region_a_name(fr={:?}, counter={})", fr, counter);
163
164         assert!(self.universal_regions.is_universal_region(fr));
165
166         let value = self.give_name_from_error_region(infcx.tcx, mir_def_id, fr, counter)
167             .or_else(|| {
168                 self.give_name_if_anonymous_region_appears_in_arguments(
169                     infcx, mir, mir_def_id, fr, counter,
170                 )
171             })
172             .or_else(|| {
173                 self.give_name_if_anonymous_region_appears_in_upvars(
174                     infcx.tcx, upvars, fr, counter,
175                 )
176             })
177             .or_else(|| {
178                 self.give_name_if_anonymous_region_appears_in_output(
179                     infcx, mir, mir_def_id, fr, counter,
180                 )
181             })
182             .or_else(|| {
183                 self.give_name_if_anonymous_region_appears_in_yield_ty(
184                     infcx, mir, mir_def_id, fr, counter,
185                 )
186             });
187
188         debug!("give_region_a_name: gave name {:?}", value);
189         value
190     }
191
192     /// Checks for the case where `fr` maps to something that the
193     /// *user* has a name for. In that case, we'll be able to map
194     /// `fr` to a `Region<'tcx>`, and that region will be one of
195     /// named variants.
196     fn give_name_from_error_region(
197         &self,
198         tcx: TyCtxt<'_, '_, 'tcx>,
199         mir_def_id: DefId,
200         fr: RegionVid,
201         counter: &mut usize,
202     ) -> Option<RegionName> {
203         let error_region = self.to_error_region(fr)?;
204
205         debug!("give_region_a_name: error_region = {:?}", error_region);
206         match error_region {
207             ty::ReEarlyBound(ebr) => {
208                 if ebr.has_name() {
209                     let span = self.get_named_span(tcx, error_region, &ebr.name);
210                     Some(RegionName {
211                         name: ebr.name,
212                         source: RegionNameSource::NamedEarlyBoundRegion(span)
213                     })
214                 } else {
215                     None
216                 }
217             }
218
219             ty::ReStatic => Some(RegionName {
220                 name: keywords::StaticLifetime.name().as_interned_str(),
221                 source: RegionNameSource::Static
222             }),
223
224             ty::ReFree(free_region) => match free_region.bound_region {
225                 ty::BoundRegion::BrNamed(_, name) => {
226                     let span = self.get_named_span(tcx, error_region, &name);
227                     Some(RegionName {
228                         name,
229                         source: RegionNameSource::NamedFreeRegion(span),
230                     })
231                 },
232
233                 ty::BoundRegion::BrEnv => {
234                     let mir_node_id = tcx.hir()
235                                          .as_local_node_id(mir_def_id)
236                                          .expect("non-local mir");
237                     let def_ty = self.universal_regions.defining_ty;
238
239                     if let DefiningTy::Closure(def_id, substs) = def_ty {
240                         let args_span = if let hir::ExprKind::Closure(_, _, _, span, _) =
241                             tcx.hir().expect_expr(mir_node_id).node
242                         {
243                             span
244                         } else {
245                             bug!("Closure is not defined by a closure expr");
246                         };
247                         let region_name = self.synthesize_region_name(counter);
248
249                         let closure_kind_ty = substs.closure_kind_ty(def_id, tcx);
250                         let note = match closure_kind_ty.to_opt_closure_kind() {
251                             Some(ty::ClosureKind::Fn) => {
252                                 "closure implements `Fn`, so references to captured variables \
253                                  can't escape the closure"
254                             }
255                             Some(ty::ClosureKind::FnMut) => {
256                                 "closure implements `FnMut`, so references to captured variables \
257                                  can't escape the closure"
258                             }
259                             Some(ty::ClosureKind::FnOnce) => {
260                                 bug!("BrEnv in a `FnOnce` closure");
261                             }
262                             None => bug!("Closure kind not inferred in borrow check"),
263                         };
264
265                         Some(RegionName {
266                             name: region_name,
267                             source: RegionNameSource::SynthesizedFreeEnvRegion(
268                                 args_span,
269                                 note.to_string()
270                             ),
271                         })
272                     } else {
273                         // Can't have BrEnv in functions, constants or generators.
274                         bug!("BrEnv outside of closure.");
275                     }
276                 }
277
278                 ty::BoundRegion::BrAnon(_) | ty::BoundRegion::BrFresh(_) => None,
279             },
280
281             ty::ReLateBound(..)
282             | ty::ReScope(..)
283             | ty::ReVar(..)
284             | ty::RePlaceholder(..)
285             | ty::ReEmpty
286             | ty::ReErased
287             | ty::ReClosureBound(..) => None,
288         }
289     }
290
291     /// Gets a span of a named region to provide context for error messages that
292     /// mention that span, for example:
293     ///
294     /// ```
295     ///  |
296     ///  | fn two_regions<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
297     ///  |                --  -- lifetime `'b` defined here
298     ///  |                |
299     ///  |                lifetime `'a` defined here
300     ///  |
301     ///  |     with_signature(cell, t, |cell, t| require(cell, t));
302     ///  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'b` must
303     ///  |                                                         outlive `'a`
304     /// ```
305     fn get_named_span(
306         &self,
307         tcx: TyCtxt<'_, '_, 'tcx>,
308         error_region: &RegionKind,
309         name: &InternedString,
310     ) -> Span {
311         let scope = error_region.free_region_binding_scope(tcx);
312         let node = tcx.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
313
314         let span = tcx.sess.source_map().def_span(tcx.hir().span_by_hir_id(node));
315         if let Some(param) = tcx.hir()
316             .get_generics(scope)
317             .and_then(|generics| generics.get_named(name))
318         {
319             param.span
320         } else {
321             span
322         }
323     }
324
325     /// Finds an argument that contains `fr` and label it with a fully
326     /// elaborated type, returning something like `'1`. Result looks
327     /// like:
328     ///
329     /// ```
330     ///  | fn foo(x: &u32) { .. }
331     ///           ------- fully elaborated type of `x` is `&'1 u32`
332     /// ```
333     fn give_name_if_anonymous_region_appears_in_arguments(
334         &self,
335         infcx: &InferCtxt<'_, '_, 'tcx>,
336         mir: &Mir<'tcx>,
337         mir_def_id: DefId,
338         fr: RegionVid,
339         counter: &mut usize,
340     ) -> Option<RegionName> {
341         let implicit_inputs = self.universal_regions.defining_ty.implicit_inputs();
342         let argument_index = self.get_argument_index_for_region(infcx.tcx, fr)?;
343
344         let arg_ty =
345             self.universal_regions.unnormalized_input_tys[implicit_inputs + argument_index];
346         if let Some(region_name) = self.give_name_if_we_can_match_hir_ty_from_argument(
347             infcx,
348             mir,
349             mir_def_id,
350             fr,
351             arg_ty,
352             argument_index,
353             counter,
354         ) {
355             return Some(region_name);
356         }
357
358         self.give_name_if_we_cannot_match_hir_ty(infcx, mir, fr, arg_ty, counter)
359     }
360
361     fn give_name_if_we_can_match_hir_ty_from_argument(
362         &self,
363         infcx: &InferCtxt<'_, '_, 'tcx>,
364         mir: &Mir<'tcx>,
365         mir_def_id: DefId,
366         needle_fr: RegionVid,
367         argument_ty: Ty<'tcx>,
368         argument_index: usize,
369         counter: &mut usize,
370     ) -> Option<RegionName> {
371         let mir_node_id = infcx.tcx.hir().as_local_node_id(mir_def_id)?;
372         let fn_decl = infcx.tcx.hir().fn_decl(mir_node_id)?;
373         let argument_hir_ty: &hir::Ty = &fn_decl.inputs[argument_index];
374         match argument_hir_ty.node {
375             // This indicates a variable with no type annotation, like
376             // `|x|`... in that case, we can't highlight the type but
377             // must highlight the variable.
378             hir::TyKind::Infer => self.give_name_if_we_cannot_match_hir_ty(
379                 infcx,
380                 mir,
381                 needle_fr,
382                 argument_ty,
383                 counter,
384             ),
385
386             _ => self.give_name_if_we_can_match_hir_ty(
387                 infcx.tcx,
388                 needle_fr,
389                 argument_ty,
390                 argument_hir_ty,
391                 counter,
392             ),
393         }
394     }
395
396     /// Attempts to highlight the specific part of a type in an argument
397     /// that has no type annotation.
398     /// For example, we might produce an annotation like this:
399     ///
400     /// ```
401     ///  |     foo(|a, b| b)
402     ///  |          -  -
403     ///  |          |  |
404     ///  |          |  has type `&'1 u32`
405     ///  |          has type `&'2 u32`
406     /// ```
407     fn give_name_if_we_cannot_match_hir_ty(
408         &self,
409         infcx: &InferCtxt<'_, '_, 'tcx>,
410         mir: &Mir<'tcx>,
411         needle_fr: RegionVid,
412         argument_ty: Ty<'tcx>,
413         counter: &mut usize,
414     ) -> Option<RegionName> {
415         let mut highlight = RegionHighlightMode::default();
416         highlight.highlighting_region_vid(needle_fr, *counter);
417         let type_name = infcx.extract_type_name(&argument_ty, Some(highlight));
418
419         debug!(
420             "give_name_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
421             type_name, needle_fr
422         );
423         let assigned_region_name = if type_name.find(&format!("'{}", counter)).is_some() {
424             // Only add a label if we can confirm that a region was labelled.
425             let argument_index = self.get_argument_index_for_region(infcx.tcx, needle_fr)?;
426             let (_, span) = self.get_argument_name_and_span_for_region(mir, argument_index);
427
428             Some(RegionName {
429                 // This counter value will already have been used, so this function will increment
430                 // it so the next value will be used next and return the region name that would
431                 // have been used.
432                 name: self.synthesize_region_name(counter),
433                 source: RegionNameSource::CannotMatchHirTy(span, type_name),
434             })
435         } else {
436             None
437         };
438
439         assigned_region_name
440     }
441
442     /// Attempts to highlight the specific part of a type annotation
443     /// that contains the anonymous reference we want to give a name
444     /// to. For example, we might produce an annotation like this:
445     ///
446     /// ```
447     ///  | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
448     ///  |                - let's call the lifetime of this reference `'1`
449     /// ```
450     ///
451     /// the way this works is that we match up `argument_ty`, which is
452     /// a `Ty<'tcx>` (the internal form of the type) with
453     /// `argument_hir_ty`, a `hir::Ty` (the syntax of the type
454     /// annotation). We are descending through the types stepwise,
455     /// looking in to find the region `needle_fr` in the internal
456     /// type. Once we find that, we can use the span of the `hir::Ty`
457     /// to add the highlight.
458     ///
459     /// This is a somewhat imperfect process, so long the way we also
460     /// keep track of the **closest** type we've found. If we fail to
461     /// find the exact `&` or `'_` to highlight, then we may fall back
462     /// to highlighting that closest type instead.
463     fn give_name_if_we_can_match_hir_ty(
464         &self,
465         tcx: TyCtxt<'_, '_, 'tcx>,
466         needle_fr: RegionVid,
467         argument_ty: Ty<'tcx>,
468         argument_hir_ty: &hir::Ty,
469         counter: &mut usize,
470     ) -> Option<RegionName> {
471         let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty)> =
472             &mut vec![(argument_ty, argument_hir_ty)];
473
474         while let Some((ty, hir_ty)) = search_stack.pop() {
475             match (&ty.sty, &hir_ty.node) {
476                 // Check if the `argument_ty` is `&'X ..` where `'X`
477                 // is the region we are looking for -- if so, and we have a `&T`
478                 // on the RHS, then we want to highlight the `&` like so:
479                 //
480                 //     &
481                 //     - let's call the lifetime of this reference `'1`
482                 (
483                     ty::Ref(region, referent_ty, _),
484                     hir::TyKind::Rptr(_lifetime, referent_hir_ty),
485                 ) => {
486                     if region.to_region_vid() == needle_fr {
487                         let region_name = self.synthesize_region_name(counter);
488
489                         // Just grab the first character, the `&`.
490                         let source_map = tcx.sess.source_map();
491                         let ampersand_span = source_map.start_point(hir_ty.span);
492
493                         return Some(RegionName {
494                             name: region_name,
495                             source: RegionNameSource::MatchedHirTy(ampersand_span),
496                         });
497                     }
498
499                     // Otherwise, let's descend into the referent types.
500                     search_stack.push((referent_ty, &referent_hir_ty.ty));
501                 }
502
503                 // Match up something like `Foo<'1>`
504                 (
505                     ty::Adt(_adt_def, substs),
506                     hir::TyKind::Path(hir::QPath::Resolved(None, path)),
507                 ) => {
508                     match path.res {
509                         // Type parameters of the type alias have no reason to
510                         // be the same as those of the ADT.
511                         // FIXME: We should be able to do something similar to
512                         // match_adt_and_segment in this case.
513                         Res::Def(DefKind::TyAlias, _) => (),
514                         _ => if let Some(last_segment) = path.segments.last() {
515                             if let Some(name) = self.match_adt_and_segment(
516                                 substs,
517                                 needle_fr,
518                                 last_segment,
519                                 counter,
520                                 search_stack,
521                             ) {
522                                 return Some(name);
523                             }
524                         }
525                     }
526                 }
527
528                 // The following cases don't have lifetimes, so we
529                 // just worry about trying to match up the rustc type
530                 // with the HIR types:
531                 (ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
532                     search_stack.extend(elem_tys.iter().map(|k| k.expect_ty()).zip(elem_hir_tys));
533                 }
534
535                 (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
536                 | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
537                     search_stack.push((elem_ty, elem_hir_ty));
538                 }
539
540                 (ty::RawPtr(mut_ty), hir::TyKind::Ptr(mut_hir_ty)) => {
541                     search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
542                 }
543
544                 _ => {
545                     // FIXME there are other cases that we could trace
546                 }
547             }
548         }
549
550         return None;
551     }
552
553     /// We've found an enum/struct/union type with the substitutions
554     /// `substs` and -- in the HIR -- a path type with the final
555     /// segment `last_segment`. Try to find a `'_` to highlight in
556     /// the generic args (or, if not, to produce new zipped pairs of
557     /// types+hir to search through).
558     fn match_adt_and_segment<'hir>(
559         &self,
560         substs: SubstsRef<'tcx>,
561         needle_fr: RegionVid,
562         last_segment: &'hir hir::PathSegment,
563         counter: &mut usize,
564         search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
565     ) -> Option<RegionName> {
566         // Did the user give explicit arguments? (e.g., `Foo<..>`)
567         let args = last_segment.args.as_ref()?;
568         let lifetime = self.try_match_adt_and_generic_args(substs, needle_fr, args, search_stack)?;
569         match lifetime.name {
570             hir::LifetimeName::Param(_)
571             | hir::LifetimeName::Error
572             | hir::LifetimeName::Static
573             | hir::LifetimeName::Underscore => {
574                 let region_name = self.synthesize_region_name(counter);
575                 let ampersand_span = lifetime.span;
576                 Some(RegionName {
577                     name: region_name,
578                     source: RegionNameSource::MatchedAdtAndSegment(ampersand_span),
579                 })
580             }
581
582             hir::LifetimeName::Implicit => {
583                 // In this case, the user left off the lifetime; so
584                 // they wrote something like:
585                 //
586                 // ```
587                 // x: Foo<T>
588                 // ```
589                 //
590                 // where the fully elaborated form is `Foo<'_, '1,
591                 // T>`. We don't consider this a match; instead we let
592                 // the "fully elaborated" type fallback above handle
593                 // it.
594                 None
595             }
596         }
597     }
598
599     /// We've found an enum/struct/union type with the substitutions
600     /// `substs` and -- in the HIR -- a path with the generic
601     /// arguments `args`. If `needle_fr` appears in the args, return
602     /// the `hir::Lifetime` that corresponds to it. If not, push onto
603     /// `search_stack` the types+hir to search through.
604     fn try_match_adt_and_generic_args<'hir>(
605         &self,
606         substs: SubstsRef<'tcx>,
607         needle_fr: RegionVid,
608         args: &'hir hir::GenericArgs,
609         search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
610     ) -> Option<&'hir hir::Lifetime> {
611         for (kind, hir_arg) in substs.iter().zip(&args.args) {
612             match (kind.unpack(), hir_arg) {
613                 (UnpackedKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
614                     if r.to_region_vid() == needle_fr {
615                         return Some(lt);
616                     }
617                 }
618
619                 (UnpackedKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
620                     search_stack.push((ty, hir_ty));
621                 }
622
623                 (UnpackedKind::Const(_ct), hir::GenericArg::Const(_hir_ct)) => {
624                     // Lifetimes cannot be found in consts, so we don't need
625                     // to search anything here.
626                 }
627
628                 (UnpackedKind::Lifetime(_), _)
629                 | (UnpackedKind::Type(_), _)
630                 | (UnpackedKind::Const(_), _) => {
631                     // I *think* that HIR lowering should ensure this
632                     // doesn't happen, even in erroneous
633                     // programs. Else we should use delay-span-bug.
634                     span_bug!(
635                         hir_arg.span(),
636                         "unmatched subst and hir arg: found {:?} vs {:?}",
637                         kind,
638                         hir_arg,
639                     );
640                 }
641             }
642         }
643
644         None
645     }
646
647     /// Finds a closure upvar that contains `fr` and label it with a
648     /// fully elaborated type, returning something like `'1`. Result
649     /// looks like:
650     ///
651     /// ```
652     ///  | let x = Some(&22);
653     ///        - fully elaborated type of `x` is `Option<&'1 u32>`
654     /// ```
655     fn give_name_if_anonymous_region_appears_in_upvars(
656         &self,
657         tcx: TyCtxt<'_, '_, 'tcx>,
658         upvars: &[Upvar],
659         fr: RegionVid,
660         counter: &mut usize,
661     ) -> Option<RegionName> {
662         let upvar_index = self.get_upvar_index_for_region(tcx, fr)?;
663         let (upvar_name, upvar_span) =
664             self.get_upvar_name_and_span_for_region(tcx, upvars, upvar_index);
665         let region_name = self.synthesize_region_name(counter);
666
667         Some(RegionName {
668             name: region_name,
669             source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name.to_string()),
670         })
671     }
672
673     /// Checks for arguments appearing in the (closure) return type. It
674     /// must be a closure since, in a free fn, such an argument would
675     /// have to either also appear in an argument (if using elision)
676     /// or be early bound (named, not in argument).
677     fn give_name_if_anonymous_region_appears_in_output(
678         &self,
679         infcx: &InferCtxt<'_, '_, 'tcx>,
680         mir: &Mir<'tcx>,
681         mir_def_id: DefId,
682         fr: RegionVid,
683         counter: &mut usize,
684     ) -> Option<RegionName> {
685         let tcx = infcx.tcx;
686
687         let return_ty = self.universal_regions.unnormalized_output_ty;
688         debug!(
689             "give_name_if_anonymous_region_appears_in_output: return_ty = {:?}",
690             return_ty
691         );
692         if !tcx.any_free_region_meets(&return_ty, |r| r.to_region_vid() == fr) {
693             return None;
694         }
695
696         let mut highlight = RegionHighlightMode::default();
697         highlight.highlighting_region_vid(fr, *counter);
698         let type_name = infcx.extract_type_name(&return_ty, Some(highlight));
699
700         let mir_node_id = tcx.hir().as_local_node_id(mir_def_id).expect("non-local mir");
701
702         let (return_span, mir_description) = match tcx.hir().get(mir_node_id) {
703             hir::Node::Expr(hir::Expr {
704                 node: hir::ExprKind::Closure(_, return_ty, _, span, gen_move),
705                 ..
706             }) => (
707                 match return_ty.output {
708                     hir::FunctionRetTy::DefaultReturn(_) => tcx.sess.source_map().end_point(*span),
709                     hir::FunctionRetTy::Return(_) => return_ty.output.span(),
710                 },
711                 if gen_move.is_some() {
712                     " of generator"
713                 } else {
714                     " of closure"
715                 },
716             ),
717             hir::Node::ImplItem(hir::ImplItem {
718                 node: hir::ImplItemKind::Method(method_sig, _),
719                 ..
720             }) => (method_sig.decl.output.span(), ""),
721             _ => (mir.span, ""),
722         };
723
724         Some(RegionName {
725             // This counter value will already have been used, so this function will increment it
726             // so the next value will be used next and return the region name that would have been
727             // used.
728             name: self.synthesize_region_name(counter),
729             source: RegionNameSource::AnonRegionFromOutput(
730                 return_span,
731                 mir_description.to_string(),
732                 type_name
733             ),
734         })
735     }
736
737     fn give_name_if_anonymous_region_appears_in_yield_ty(
738         &self,
739         infcx: &InferCtxt<'_, '_, 'tcx>,
740         mir: &Mir<'tcx>,
741         mir_def_id: DefId,
742         fr: RegionVid,
743         counter: &mut usize,
744     ) -> Option<RegionName> {
745         // Note: generators from `async fn` yield `()`, so we don't have to
746         // worry about them here.
747         let yield_ty = self.universal_regions.yield_ty?;
748         debug!(
749             "give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}",
750             yield_ty,
751         );
752
753         let tcx = infcx.tcx;
754
755         if !tcx.any_free_region_meets(&yield_ty, |r| r.to_region_vid() == fr) {
756             return None;
757         }
758
759         let mut highlight = RegionHighlightMode::default();
760         highlight.highlighting_region_vid(fr, *counter);
761         let type_name = infcx.extract_type_name(&yield_ty, Some(highlight));
762
763         let mir_node_id = tcx.hir().as_local_node_id(mir_def_id).expect("non-local mir");
764
765         let yield_span = match tcx.hir().get(mir_node_id) {
766             hir::Node::Expr(hir::Expr {
767                 node: hir::ExprKind::Closure(_, _, _, span, _),
768                 ..
769             }) => (
770                 tcx.sess.source_map().end_point(*span)
771             ),
772             _ => mir.span,
773         };
774
775         debug!(
776             "give_name_if_anonymous_region_appears_in_yield_ty: \
777              type_name = {:?}, yield_span = {:?}",
778             yield_span,
779             type_name,
780         );
781
782         Some(RegionName {
783             name: self.synthesize_region_name(counter),
784             source: RegionNameSource::AnonRegionFromYieldTy(yield_span, type_name),
785         })
786     }
787
788     /// Creates a synthetic region named `'1`, incrementing the
789     /// counter.
790     fn synthesize_region_name(&self, counter: &mut usize) -> InternedString {
791         let c = *counter;
792         *counter += 1;
793
794         Name::intern(&format!("'{:?}", c)).as_interned_str()
795     }
796 }