]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs
Auto merge of #63869 - GuillaumeGomez:fix-build-failure, r=Mark-Simulacrum
[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::Body;
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::symbol::kw;
16 use syntax_pos::Span;
17 use syntax_pos::symbol::InternedString;
18
19 #[derive(Debug)]
20 crate struct RegionName {
21     crate name: InternedString,
22     crate source: RegionNameSource,
23 }
24
25 #[derive(Debug)]
26 crate enum RegionNameSource {
27     NamedEarlyBoundRegion(Span),
28     NamedFreeRegion(Span),
29     Static,
30     SynthesizedFreeEnvRegion(Span, String),
31     CannotMatchHirTy(Span, String),
32     MatchedHirTy(Span),
33     MatchedAdtAndSegment(Span),
34     AnonRegionFromUpvar(Span, String),
35     AnonRegionFromOutput(Span, String, String),
36     AnonRegionFromYieldTy(Span, String),
37 }
38
39 impl RegionName {
40     #[allow(dead_code)]
41     crate fn was_named(&self) -> bool {
42         match self.source {
43             RegionNameSource::NamedEarlyBoundRegion(..) |
44             RegionNameSource::NamedFreeRegion(..) |
45             RegionNameSource::Static => true,
46             RegionNameSource::SynthesizedFreeEnvRegion(..) |
47             RegionNameSource::CannotMatchHirTy(..) |
48             RegionNameSource::MatchedHirTy(..) |
49             RegionNameSource::MatchedAdtAndSegment(..) |
50             RegionNameSource::AnonRegionFromUpvar(..) |
51             RegionNameSource::AnonRegionFromOutput(..) |
52             RegionNameSource::AnonRegionFromYieldTy(..) => false,
53         }
54     }
55
56     #[allow(dead_code)]
57     crate fn was_synthesized(&self) -> bool {
58         !self.was_named()
59     }
60
61     #[allow(dead_code)]
62     crate fn name(&self) -> InternedString {
63         self.name
64     }
65
66     crate fn highlight_region_name(
67         &self,
68         diag: &mut DiagnosticBuilder<'_>
69     ) {
70         match &self.source {
71             RegionNameSource::NamedFreeRegion(span) |
72             RegionNameSource::NamedEarlyBoundRegion(span) => {
73                 diag.span_label(
74                     *span,
75                     format!("lifetime `{}` defined here", self),
76                 );
77             },
78             RegionNameSource::SynthesizedFreeEnvRegion(span, note) => {
79                 diag.span_label(
80                     *span,
81                     format!("lifetime `{}` represents this closure's body", self),
82                 );
83                 diag.note(&note);
84             },
85             RegionNameSource::CannotMatchHirTy(span, type_name) => {
86                 diag.span_label(*span, format!("has type `{}`", type_name));
87             },
88             RegionNameSource::MatchedHirTy(span) => {
89                 diag.span_label(
90                     *span,
91                     format!("let's call the lifetime of this reference `{}`", self),
92                 );
93             },
94             RegionNameSource::MatchedAdtAndSegment(span) => {
95                 diag.span_label(*span, format!("let's call this `{}`", self));
96             },
97             RegionNameSource::AnonRegionFromUpvar(span, upvar_name) => {
98                 diag.span_label(
99                     *span,
100                     format!("lifetime `{}` appears in the type of `{}`", self, upvar_name),
101                 );
102             },
103             RegionNameSource::AnonRegionFromOutput(span, mir_description, type_name) => {
104                 diag.span_label(
105                     *span,
106                     format!("return type{} is {}", mir_description, type_name),
107                 );
108             },
109             RegionNameSource::AnonRegionFromYieldTy(span, type_name) => {
110                 diag.span_label(
111                     *span,
112                     format!("yield type is {}", type_name),
113                 );
114             }
115             RegionNameSource::Static => {},
116         }
117     }
118 }
119
120 impl Display for RegionName {
121     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122         write!(f, "{}", self.name)
123     }
124 }
125
126 impl<'tcx> RegionInferenceContext<'tcx> {
127     /// Maps from an internal MIR region vid to something that we can
128     /// report to the user. In some cases, the region vids will map
129     /// directly to lifetimes that the user has a name for (e.g.,
130     /// `'static`). But frequently they will not, in which case we
131     /// have to find some way to identify the lifetime to the user. To
132     /// that end, this function takes a "diagnostic" so that it can
133     /// create auxiliary notes as needed.
134     ///
135     /// Example (function arguments):
136     ///
137     /// Suppose we are trying to give a name to the lifetime of the
138     /// reference `x`:
139     ///
140     /// ```
141     /// fn foo(x: &u32) { .. }
142     /// ```
143     ///
144     /// This function would create a label like this:
145     ///
146     /// ```
147     ///  | fn foo(x: &u32) { .. }
148     ///           ------- fully elaborated type of `x` is `&'1 u32`
149     /// ```
150     ///
151     /// and then return the name `'1` for us to use.
152     crate fn give_region_a_name(
153         &self,
154         infcx: &InferCtxt<'_, 'tcx>,
155         body: &Body<'tcx>,
156         upvars: &[Upvar],
157         mir_def_id: DefId,
158         fr: RegionVid,
159         counter: &mut usize,
160     ) -> Option<RegionName> {
161         debug!("give_region_a_name(fr={:?}, counter={})", fr, counter);
162
163         assert!(self.universal_regions.is_universal_region(fr));
164
165         let value = self.give_name_from_error_region(infcx.tcx, mir_def_id, fr, counter)
166             .or_else(|| {
167                 self.give_name_if_anonymous_region_appears_in_arguments(
168                     infcx, body, mir_def_id, fr, counter,
169                 )
170             })
171             .or_else(|| {
172                 self.give_name_if_anonymous_region_appears_in_upvars(
173                     infcx.tcx, upvars, fr, counter,
174                 )
175             })
176             .or_else(|| {
177                 self.give_name_if_anonymous_region_appears_in_output(
178                     infcx, body, mir_def_id, fr, counter,
179                 )
180             })
181             .or_else(|| {
182                 self.give_name_if_anonymous_region_appears_in_yield_ty(
183                     infcx, body, mir_def_id, fr, counter,
184                 )
185             });
186
187         debug!("give_region_a_name: gave name {:?}", value);
188         value
189     }
190
191     /// Checks for the case where `fr` maps to something that the
192     /// *user* has a name for. In that case, we'll be able to map
193     /// `fr` to a `Region<'tcx>`, and that region will be one of
194     /// named variants.
195     fn give_name_from_error_region(
196         &self,
197         tcx: TyCtxt<'tcx>,
198         mir_def_id: DefId,
199         fr: RegionVid,
200         counter: &mut usize,
201     ) -> Option<RegionName> {
202         let error_region = self.to_error_region(fr)?;
203
204         debug!("give_region_a_name: error_region = {:?}", error_region);
205         match error_region {
206             ty::ReEarlyBound(ebr) => {
207                 if ebr.has_name() {
208                     let span = self.get_named_span(tcx, error_region, ebr.name);
209                     Some(RegionName {
210                         name: ebr.name,
211                         source: RegionNameSource::NamedEarlyBoundRegion(span)
212                     })
213                 } else {
214                     None
215                 }
216             }
217
218             ty::ReStatic => Some(RegionName {
219                 name: kw::StaticLifetime.as_interned_str(),
220                 source: RegionNameSource::Static
221             }),
222
223             ty::ReFree(free_region) => match free_region.bound_region {
224                 ty::BoundRegion::BrNamed(_, name) => {
225                     let span = self.get_named_span(tcx, error_region, name);
226                     Some(RegionName {
227                         name,
228                         source: RegionNameSource::NamedFreeRegion(span),
229                     })
230                 },
231
232                 ty::BoundRegion::BrEnv => {
233                     let mir_hir_id = tcx.hir()
234                                         .as_local_hir_id(mir_def_id)
235                                         .expect("non-local mir");
236                     let def_ty = self.universal_regions.defining_ty;
237
238                     if let DefiningTy::Closure(def_id, substs) = def_ty {
239                         let args_span = if let hir::ExprKind::Closure(_, _, _, span, _) =
240                             tcx.hir().expect_expr(mir_hir_id).node
241                         {
242                             span
243                         } else {
244                             bug!("Closure is not defined by a closure expr");
245                         };
246                         let region_name = self.synthesize_region_name(counter);
247
248                         let closure_kind_ty = substs.closure_kind_ty(def_id, tcx);
249                         let note = match closure_kind_ty.to_opt_closure_kind() {
250                             Some(ty::ClosureKind::Fn) => {
251                                 "closure implements `Fn`, so references to captured variables \
252                                  can't escape the closure"
253                             }
254                             Some(ty::ClosureKind::FnMut) => {
255                                 "closure implements `FnMut`, so references to captured variables \
256                                  can't escape the closure"
257                             }
258                             Some(ty::ClosureKind::FnOnce) => {
259                                 bug!("BrEnv in a `FnOnce` closure");
260                             }
261                             None => bug!("Closure kind not inferred in borrow check"),
262                         };
263
264                         Some(RegionName {
265                             name: region_name,
266                             source: RegionNameSource::SynthesizedFreeEnvRegion(
267                                 args_span,
268                                 note.to_string()
269                             ),
270                         })
271                     } else {
272                         // Can't have BrEnv in functions, constants or generators.
273                         bug!("BrEnv outside of closure.");
274                     }
275                 }
276
277                 ty::BoundRegion::BrAnon(_) => None,
278             },
279
280             ty::ReLateBound(..)
281             | ty::ReScope(..)
282             | ty::ReVar(..)
283             | ty::RePlaceholder(..)
284             | ty::ReEmpty
285             | ty::ReErased
286             | ty::ReClosureBound(..) => None,
287         }
288     }
289
290     /// Gets a span of a named region to provide context for error messages that
291     /// mention that span, for example:
292     ///
293     /// ```
294     ///  |
295     ///  | fn two_regions<'a, 'b, T>(cell: Cell<&'a ()>, t: T)
296     ///  |                --  -- lifetime `'b` defined here
297     ///  |                |
298     ///  |                lifetime `'a` defined here
299     ///  |
300     ///  |     with_signature(cell, t, |cell, t| require(cell, t));
301     ///  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ argument requires that `'b` must
302     ///  |                                                         outlive `'a`
303     /// ```
304     fn get_named_span(
305         &self,
306         tcx: TyCtxt<'tcx>,
307         error_region: &RegionKind,
308         name: InternedString,
309     ) -> Span {
310         let scope = error_region.free_region_binding_scope(tcx);
311         let node = tcx.hir().as_local_hir_id(scope).unwrap_or(hir::DUMMY_HIR_ID);
312
313         let span = tcx.sess.source_map().def_span(tcx.hir().span(node));
314         if let Some(param) = tcx.hir()
315             .get_generics(scope)
316             .and_then(|generics| generics.get_named(name))
317         {
318             param.span
319         } else {
320             span
321         }
322     }
323
324     /// Finds an argument that contains `fr` and label it with a fully
325     /// elaborated type, returning something like `'1`. Result looks
326     /// like:
327     ///
328     /// ```
329     ///  | fn foo(x: &u32) { .. }
330     ///           ------- fully elaborated type of `x` is `&'1 u32`
331     /// ```
332     fn give_name_if_anonymous_region_appears_in_arguments(
333         &self,
334         infcx: &InferCtxt<'_, 'tcx>,
335         body: &Body<'tcx>,
336         mir_def_id: DefId,
337         fr: RegionVid,
338         counter: &mut usize,
339     ) -> Option<RegionName> {
340         let implicit_inputs = self.universal_regions.defining_ty.implicit_inputs();
341         let argument_index = self.get_argument_index_for_region(infcx.tcx, fr)?;
342
343         let arg_ty =
344             self.universal_regions.unnormalized_input_tys[implicit_inputs + argument_index];
345         if let Some(region_name) = self.give_name_if_we_can_match_hir_ty_from_argument(
346             infcx,
347             body,
348             mir_def_id,
349             fr,
350             arg_ty,
351             argument_index,
352             counter,
353         ) {
354             return Some(region_name);
355         }
356
357         self.give_name_if_we_cannot_match_hir_ty(infcx, body, fr, arg_ty, counter)
358     }
359
360     fn give_name_if_we_can_match_hir_ty_from_argument(
361         &self,
362         infcx: &InferCtxt<'_, 'tcx>,
363         body: &Body<'tcx>,
364         mir_def_id: DefId,
365         needle_fr: RegionVid,
366         argument_ty: Ty<'tcx>,
367         argument_index: usize,
368         counter: &mut usize,
369     ) -> Option<RegionName> {
370         let mir_hir_id = infcx.tcx.hir().as_local_hir_id(mir_def_id)?;
371         let fn_decl = infcx.tcx.hir().fn_decl_by_hir_id(mir_hir_id)?;
372         let argument_hir_ty: &hir::Ty = &fn_decl.inputs[argument_index];
373         match argument_hir_ty.node {
374             // This indicates a variable with no type annotation, like
375             // `|x|`... in that case, we can't highlight the type but
376             // must highlight the variable.
377             hir::TyKind::Infer => self.give_name_if_we_cannot_match_hir_ty(
378                 infcx,
379                 body,
380                 needle_fr,
381                 argument_ty,
382                 counter,
383             ),
384
385             _ => self.give_name_if_we_can_match_hir_ty(
386                 infcx.tcx,
387                 needle_fr,
388                 argument_ty,
389                 argument_hir_ty,
390                 counter,
391             ),
392         }
393     }
394
395     /// Attempts to highlight the specific part of a type in an argument
396     /// that has no type annotation.
397     /// For example, we might produce an annotation like this:
398     ///
399     /// ```
400     ///  |     foo(|a, b| b)
401     ///  |          -  -
402     ///  |          |  |
403     ///  |          |  has type `&'1 u32`
404     ///  |          has type `&'2 u32`
405     /// ```
406     fn give_name_if_we_cannot_match_hir_ty(
407         &self,
408         infcx: &InferCtxt<'_, 'tcx>,
409         body: &Body<'tcx>,
410         needle_fr: RegionVid,
411         argument_ty: Ty<'tcx>,
412         counter: &mut usize,
413     ) -> Option<RegionName> {
414         let mut highlight = RegionHighlightMode::default();
415         highlight.highlighting_region_vid(needle_fr, *counter);
416         let type_name = infcx.extract_type_name(&argument_ty, Some(highlight)).0;
417
418         debug!(
419             "give_name_if_we_cannot_match_hir_ty: type_name={:?} needle_fr={:?}",
420             type_name, needle_fr
421         );
422         let assigned_region_name = if type_name.find(&format!("'{}", counter)).is_some() {
423             // Only add a label if we can confirm that a region was labelled.
424             let argument_index = self.get_argument_index_for_region(infcx.tcx, needle_fr)?;
425             let (_, span) = self.get_argument_name_and_span_for_region(body, argument_index);
426
427             Some(RegionName {
428                 // This counter value will already have been used, so this function will increment
429                 // it so the next value will be used next and return the region name that would
430                 // have been used.
431                 name: self.synthesize_region_name(counter),
432                 source: RegionNameSource::CannotMatchHirTy(span, type_name),
433             })
434         } else {
435             None
436         };
437
438         assigned_region_name
439     }
440
441     /// Attempts to highlight the specific part of a type annotation
442     /// that contains the anonymous reference we want to give a name
443     /// to. For example, we might produce an annotation like this:
444     ///
445     /// ```
446     ///  | fn a<T>(items: &[T]) -> Box<dyn Iterator<Item = &T>> {
447     ///  |                - let's call the lifetime of this reference `'1`
448     /// ```
449     ///
450     /// the way this works is that we match up `argument_ty`, which is
451     /// a `Ty<'tcx>` (the internal form of the type) with
452     /// `argument_hir_ty`, a `hir::Ty` (the syntax of the type
453     /// annotation). We are descending through the types stepwise,
454     /// looking in to find the region `needle_fr` in the internal
455     /// type. Once we find that, we can use the span of the `hir::Ty`
456     /// to add the highlight.
457     ///
458     /// This is a somewhat imperfect process, so long the way we also
459     /// keep track of the **closest** type we've found. If we fail to
460     /// find the exact `&` or `'_` to highlight, then we may fall back
461     /// to highlighting that closest type instead.
462     fn give_name_if_we_can_match_hir_ty(
463         &self,
464         tcx: TyCtxt<'tcx>,
465         needle_fr: RegionVid,
466         argument_ty: Ty<'tcx>,
467         argument_hir_ty: &hir::Ty,
468         counter: &mut usize,
469     ) -> Option<RegionName> {
470         let search_stack: &mut Vec<(Ty<'tcx>, &hir::Ty)> =
471             &mut vec![(argument_ty, argument_hir_ty)];
472
473         while let Some((ty, hir_ty)) = search_stack.pop() {
474             match (&ty.sty, &hir_ty.node) {
475                 // Check if the `argument_ty` is `&'X ..` where `'X`
476                 // is the region we are looking for -- if so, and we have a `&T`
477                 // on the RHS, then we want to highlight the `&` like so:
478                 //
479                 //     &
480                 //     - let's call the lifetime of this reference `'1`
481                 (
482                     ty::Ref(region, referent_ty, _),
483                     hir::TyKind::Rptr(_lifetime, referent_hir_ty),
484                 ) => {
485                     if region.to_region_vid() == needle_fr {
486                         let region_name = self.synthesize_region_name(counter);
487
488                         // Just grab the first character, the `&`.
489                         let source_map = tcx.sess.source_map();
490                         let ampersand_span = source_map.start_point(hir_ty.span);
491
492                         return Some(RegionName {
493                             name: region_name,
494                             source: RegionNameSource::MatchedHirTy(ampersand_span),
495                         });
496                     }
497
498                     // Otherwise, let's descend into the referent types.
499                     search_stack.push((referent_ty, &referent_hir_ty.ty));
500                 }
501
502                 // Match up something like `Foo<'1>`
503                 (
504                     ty::Adt(_adt_def, substs),
505                     hir::TyKind::Path(hir::QPath::Resolved(None, path)),
506                 ) => {
507                     match path.res {
508                         // Type parameters of the type alias have no reason to
509                         // be the same as those of the ADT.
510                         // FIXME: We should be able to do something similar to
511                         // match_adt_and_segment in this case.
512                         Res::Def(DefKind::TyAlias, _) => (),
513                         _ => if let Some(last_segment) = path.segments.last() {
514                             if let Some(name) = self.match_adt_and_segment(
515                                 substs,
516                                 needle_fr,
517                                 last_segment,
518                                 counter,
519                                 search_stack,
520                             ) {
521                                 return Some(name);
522                             }
523                         }
524                     }
525                 }
526
527                 // The following cases don't have lifetimes, so we
528                 // just worry about trying to match up the rustc type
529                 // with the HIR types:
530                 (ty::Tuple(elem_tys), hir::TyKind::Tup(elem_hir_tys)) => {
531                     search_stack.extend(elem_tys.iter().map(|k| k.expect_ty()).zip(elem_hir_tys));
532                 }
533
534                 (ty::Slice(elem_ty), hir::TyKind::Slice(elem_hir_ty))
535                 | (ty::Array(elem_ty, _), hir::TyKind::Array(elem_hir_ty, _)) => {
536                     search_stack.push((elem_ty, elem_hir_ty));
537                 }
538
539                 (ty::RawPtr(mut_ty), hir::TyKind::Ptr(mut_hir_ty)) => {
540                     search_stack.push((mut_ty.ty, &mut_hir_ty.ty));
541                 }
542
543                 _ => {
544                     // FIXME there are other cases that we could trace
545                 }
546             }
547         }
548
549         return None;
550     }
551
552     /// We've found an enum/struct/union type with the substitutions
553     /// `substs` and -- in the HIR -- a path type with the final
554     /// segment `last_segment`. Try to find a `'_` to highlight in
555     /// the generic args (or, if not, to produce new zipped pairs of
556     /// types+hir to search through).
557     fn match_adt_and_segment<'hir>(
558         &self,
559         substs: SubstsRef<'tcx>,
560         needle_fr: RegionVid,
561         last_segment: &'hir hir::PathSegment,
562         counter: &mut usize,
563         search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
564     ) -> Option<RegionName> {
565         // Did the user give explicit arguments? (e.g., `Foo<..>`)
566         let args = last_segment.args.as_ref()?;
567         let lifetime = self.try_match_adt_and_generic_args(substs, needle_fr, args, search_stack)?;
568         match lifetime.name {
569             hir::LifetimeName::Param(_)
570             | hir::LifetimeName::Error
571             | hir::LifetimeName::Static
572             | hir::LifetimeName::Underscore => {
573                 let region_name = self.synthesize_region_name(counter);
574                 let ampersand_span = lifetime.span;
575                 Some(RegionName {
576                     name: region_name,
577                     source: RegionNameSource::MatchedAdtAndSegment(ampersand_span),
578                 })
579             }
580
581             hir::LifetimeName::ImplicitObjectLifetimeDefault
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         body: &Body<'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)).0;
699
700         let mir_hir_id = tcx.hir().as_local_hir_id(mir_def_id).expect("non-local mir");
701
702         let (return_span, mir_description) = match tcx.hir().get(mir_hir_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             _ => (body.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         body: &Body<'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)).0;
762
763         let mir_hir_id = tcx.hir().as_local_hir_id(mir_def_id).expect("non-local mir");
764
765         let yield_span = match tcx.hir().get(mir_hir_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             _ => body.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         InternedString::intern(&format!("'{:?}", c))
795     }
796 }