]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/nll/region_infer/error_reporting/region_name.rs
Rollup merge of #60981 - alexcrichton:update-compiler-builtins, r=cuviper
[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::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         mir: &Mir<'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, mir, 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, mir, mir_def_id, fr, counter,
179                 )
180             })
181             .or_else(|| {
182                 self.give_name_if_anonymous_region_appears_in_yield_ty(
183                     infcx, mir, 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_node_id = tcx.hir()
234                                          .as_local_node_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_node_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(_) | ty::BoundRegion::BrFresh(_) => 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_by_hir_id(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         mir: &Mir<'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             mir,
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, mir, 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         mir: &Mir<'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_node_id = infcx.tcx.hir().as_local_node_id(mir_def_id)?;
371         let fn_decl = infcx.tcx.hir().fn_decl(mir_node_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                 mir,
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         mir: &Mir<'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));
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(mir, 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::Implicit => {
582                 // In this case, the user left off the lifetime; so
583                 // they wrote something like:
584                 //
585                 // ```
586                 // x: Foo<T>
587                 // ```
588                 //
589                 // where the fully elaborated form is `Foo<'_, '1,
590                 // T>`. We don't consider this a match; instead we let
591                 // the "fully elaborated" type fallback above handle
592                 // it.
593                 None
594             }
595         }
596     }
597
598     /// We've found an enum/struct/union type with the substitutions
599     /// `substs` and -- in the HIR -- a path with the generic
600     /// arguments `args`. If `needle_fr` appears in the args, return
601     /// the `hir::Lifetime` that corresponds to it. If not, push onto
602     /// `search_stack` the types+hir to search through.
603     fn try_match_adt_and_generic_args<'hir>(
604         &self,
605         substs: SubstsRef<'tcx>,
606         needle_fr: RegionVid,
607         args: &'hir hir::GenericArgs,
608         search_stack: &mut Vec<(Ty<'tcx>, &'hir hir::Ty)>,
609     ) -> Option<&'hir hir::Lifetime> {
610         for (kind, hir_arg) in substs.iter().zip(&args.args) {
611             match (kind.unpack(), hir_arg) {
612                 (UnpackedKind::Lifetime(r), hir::GenericArg::Lifetime(lt)) => {
613                     if r.to_region_vid() == needle_fr {
614                         return Some(lt);
615                     }
616                 }
617
618                 (UnpackedKind::Type(ty), hir::GenericArg::Type(hir_ty)) => {
619                     search_stack.push((ty, hir_ty));
620                 }
621
622                 (UnpackedKind::Const(_ct), hir::GenericArg::Const(_hir_ct)) => {
623                     // Lifetimes cannot be found in consts, so we don't need
624                     // to search anything here.
625                 }
626
627                 (UnpackedKind::Lifetime(_), _)
628                 | (UnpackedKind::Type(_), _)
629                 | (UnpackedKind::Const(_), _) => {
630                     // I *think* that HIR lowering should ensure this
631                     // doesn't happen, even in erroneous
632                     // programs. Else we should use delay-span-bug.
633                     span_bug!(
634                         hir_arg.span(),
635                         "unmatched subst and hir arg: found {:?} vs {:?}",
636                         kind,
637                         hir_arg,
638                     );
639                 }
640             }
641         }
642
643         None
644     }
645
646     /// Finds a closure upvar that contains `fr` and label it with a
647     /// fully elaborated type, returning something like `'1`. Result
648     /// looks like:
649     ///
650     /// ```
651     ///  | let x = Some(&22);
652     ///        - fully elaborated type of `x` is `Option<&'1 u32>`
653     /// ```
654     fn give_name_if_anonymous_region_appears_in_upvars(
655         &self,
656         tcx: TyCtxt<'_, '_, 'tcx>,
657         upvars: &[Upvar],
658         fr: RegionVid,
659         counter: &mut usize,
660     ) -> Option<RegionName> {
661         let upvar_index = self.get_upvar_index_for_region(tcx, fr)?;
662         let (upvar_name, upvar_span) =
663             self.get_upvar_name_and_span_for_region(tcx, upvars, upvar_index);
664         let region_name = self.synthesize_region_name(counter);
665
666         Some(RegionName {
667             name: region_name,
668             source: RegionNameSource::AnonRegionFromUpvar(upvar_span, upvar_name.to_string()),
669         })
670     }
671
672     /// Checks for arguments appearing in the (closure) return type. It
673     /// must be a closure since, in a free fn, such an argument would
674     /// have to either also appear in an argument (if using elision)
675     /// or be early bound (named, not in argument).
676     fn give_name_if_anonymous_region_appears_in_output(
677         &self,
678         infcx: &InferCtxt<'_, '_, 'tcx>,
679         mir: &Mir<'tcx>,
680         mir_def_id: DefId,
681         fr: RegionVid,
682         counter: &mut usize,
683     ) -> Option<RegionName> {
684         let tcx = infcx.tcx;
685
686         let return_ty = self.universal_regions.unnormalized_output_ty;
687         debug!(
688             "give_name_if_anonymous_region_appears_in_output: return_ty = {:?}",
689             return_ty
690         );
691         if !tcx.any_free_region_meets(&return_ty, |r| r.to_region_vid() == fr) {
692             return None;
693         }
694
695         let mut highlight = RegionHighlightMode::default();
696         highlight.highlighting_region_vid(fr, *counter);
697         let type_name = infcx.extract_type_name(&return_ty, Some(highlight));
698
699         let mir_node_id = tcx.hir().as_local_node_id(mir_def_id).expect("non-local mir");
700
701         let (return_span, mir_description) = match tcx.hir().get(mir_node_id) {
702             hir::Node::Expr(hir::Expr {
703                 node: hir::ExprKind::Closure(_, return_ty, _, span, gen_move),
704                 ..
705             }) => (
706                 match return_ty.output {
707                     hir::FunctionRetTy::DefaultReturn(_) => tcx.sess.source_map().end_point(*span),
708                     hir::FunctionRetTy::Return(_) => return_ty.output.span(),
709                 },
710                 if gen_move.is_some() {
711                     " of generator"
712                 } else {
713                     " of closure"
714                 },
715             ),
716             hir::Node::ImplItem(hir::ImplItem {
717                 node: hir::ImplItemKind::Method(method_sig, _),
718                 ..
719             }) => (method_sig.decl.output.span(), ""),
720             _ => (mir.span, ""),
721         };
722
723         Some(RegionName {
724             // This counter value will already have been used, so this function will increment it
725             // so the next value will be used next and return the region name that would have been
726             // used.
727             name: self.synthesize_region_name(counter),
728             source: RegionNameSource::AnonRegionFromOutput(
729                 return_span,
730                 mir_description.to_string(),
731                 type_name
732             ),
733         })
734     }
735
736     fn give_name_if_anonymous_region_appears_in_yield_ty(
737         &self,
738         infcx: &InferCtxt<'_, '_, 'tcx>,
739         mir: &Mir<'tcx>,
740         mir_def_id: DefId,
741         fr: RegionVid,
742         counter: &mut usize,
743     ) -> Option<RegionName> {
744         // Note: generators from `async fn` yield `()`, so we don't have to
745         // worry about them here.
746         let yield_ty = self.universal_regions.yield_ty?;
747         debug!(
748             "give_name_if_anonymous_region_appears_in_yield_ty: yield_ty = {:?}",
749             yield_ty,
750         );
751
752         let tcx = infcx.tcx;
753
754         if !tcx.any_free_region_meets(&yield_ty, |r| r.to_region_vid() == fr) {
755             return None;
756         }
757
758         let mut highlight = RegionHighlightMode::default();
759         highlight.highlighting_region_vid(fr, *counter);
760         let type_name = infcx.extract_type_name(&yield_ty, Some(highlight));
761
762         let mir_node_id = tcx.hir().as_local_node_id(mir_def_id).expect("non-local mir");
763
764         let yield_span = match tcx.hir().get(mir_node_id) {
765             hir::Node::Expr(hir::Expr {
766                 node: hir::ExprKind::Closure(_, _, _, span, _),
767                 ..
768             }) => (
769                 tcx.sess.source_map().end_point(*span)
770             ),
771             _ => mir.span,
772         };
773
774         debug!(
775             "give_name_if_anonymous_region_appears_in_yield_ty: \
776              type_name = {:?}, yield_span = {:?}",
777             yield_span,
778             type_name,
779         );
780
781         Some(RegionName {
782             name: self.synthesize_region_name(counter),
783             source: RegionNameSource::AnonRegionFromYieldTy(yield_span, type_name),
784         })
785     }
786
787     /// Creates a synthetic region named `'1`, incrementing the
788     /// counter.
789     fn synthesize_region_name(&self, counter: &mut usize) -> InternedString {
790         let c = *counter;
791         *counter += 1;
792
793         InternedString::intern(&format!("'{:?}", c))
794     }
795 }