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