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