]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/borrow_check/region_infer/opaque_types.rs
Auto merge of #69590 - Dylan-DPC:rollup-i3z0sic, r=Dylan-DPC
[rust.git] / src / librustc_mir / borrow_check / region_infer / opaque_types.rs
1 use rustc::ty::{self, TyCtxt, TypeFoldable};
2 use rustc_data_structures::fx::FxHashMap;
3 use rustc_hir::def_id::DefId;
4 use rustc_infer::infer::InferCtxt;
5 use rustc_span::Span;
6
7 use super::RegionInferenceContext;
8
9 impl<'tcx> RegionInferenceContext<'tcx> {
10     /// Resolve any opaque types that were encountered while borrow checking
11     /// this item. This is then used to get the type in the `type_of` query.
12     ///
13     /// For example consider `fn f<'a>(x: &'a i32) -> impl Sized + 'a { x }`.
14     /// This is lowered to give HIR something like
15     ///
16     /// type f<'a>::_Return<'_a> = impl Sized + '_a;
17     /// fn f<'a>(x: &'a i32) -> f<'static>::_Return<'a> { x }
18     ///
19     /// When checking the return type record the type from the return and the
20     /// type used in the return value. In this case they might be `_Return<'1>`
21     /// and `&'2 i32` respectively.
22     ///
23     /// Once we to this method, we have completed region inference and want to
24     /// call `infer_opaque_definition_from_instantiation` to get the inferred
25     /// type of `_Return<'_a>`. `infer_opaque_definition_from_instantiation`
26     /// compares lifetimes directly, so we need to map the inference variables
27     /// back to concrete lifetimes: `'static`, `ReEarlyBound` or `ReFree`.
28     ///
29     /// First we map all the lifetimes in the concrete type to an equal
30     /// universal region that occurs in the concrete type's substs, in this case
31     /// this would result in `&'1 i32`. We only consider regions in the substs
32     /// in case there is an equal region that does not. For example, this should
33     /// be allowed:
34     /// `fn f<'a: 'b, 'b: 'a>(x: *mut &'b i32) -> impl Sized + 'a { x }`
35     ///
36     /// Then we map the regions in both the type and the subst to their
37     /// `external_name` giving `concrete_type = &'a i32`,
38     /// `substs = ['static, 'a]`. This will then allow
39     /// `infer_opaque_definition_from_instantiation` to determine that
40     /// `_Return<'_a> = &'_a i32`.
41     ///
42     /// There's a slight complication around closures. Given
43     /// `fn f<'a: 'a>() { || {} }` the closure's type is something like
44     /// `f::<'a>::{{closure}}`. The region parameter from f is essentially
45     /// ignored by type checking so ends up being inferred to an empty region.
46     /// Calling `universal_upper_bound` for such a region gives `fr_fn_body`,
47     /// which has no `external_name` in which case we use `'empty` as the
48     /// region to pass to `infer_opaque_definition_from_instantiation`.
49     pub(in crate::borrow_check) fn infer_opaque_types(
50         &self,
51         infcx: &InferCtxt<'_, 'tcx>,
52         opaque_ty_decls: FxHashMap<DefId, ty::ResolvedOpaqueTy<'tcx>>,
53         span: Span,
54     ) -> FxHashMap<DefId, ty::ResolvedOpaqueTy<'tcx>> {
55         opaque_ty_decls
56             .into_iter()
57             .map(|(opaque_def_id, ty::ResolvedOpaqueTy { concrete_type, substs })| {
58                 debug!(
59                     "infer_opaque_types(concrete_type = {:?}, substs = {:?})",
60                     concrete_type, substs
61                 );
62
63                 let mut subst_regions = vec![self.universal_regions.fr_static];
64                 let universal_substs =
65                     infcx.tcx.fold_regions(&substs, &mut false, |region, _| match *region {
66                         ty::ReVar(vid) => {
67                             subst_regions.push(vid);
68                             self.definitions[vid].external_name.unwrap_or_else(|| {
69                                 infcx.tcx.sess.delay_span_bug(
70                                     span,
71                                     "opaque type with non-universal region substs",
72                                 );
73                                 infcx.tcx.lifetimes.re_static
74                             })
75                         }
76                         // We don't fold regions in the predicates of opaque
77                         // types to `ReVar`s. This means that in a case like
78                         //
79                         // fn f<'a: 'a>() -> impl Iterator<Item = impl Sized>
80                         //
81                         // The inner opaque type has `'static` in its substs.
82                         ty::ReStatic => region,
83                         _ => {
84                             infcx.tcx.sess.delay_span_bug(
85                                 span,
86                                 &format!("unexpected concrete region in borrowck: {:?}", region),
87                             );
88                             region
89                         }
90                     });
91
92                 subst_regions.sort();
93                 subst_regions.dedup();
94
95                 let universal_concrete_type =
96                     infcx.tcx.fold_regions(&concrete_type, &mut false, |region, _| match *region {
97                         ty::ReVar(vid) => subst_regions
98                             .iter()
99                             .find(|ur_vid| self.eval_equal(vid, **ur_vid))
100                             .and_then(|ur_vid| self.definitions[*ur_vid].external_name)
101                             .unwrap_or(infcx.tcx.lifetimes.re_root_empty),
102                         ty::ReLateBound(..) => region,
103                         _ => {
104                             infcx.tcx.sess.delay_span_bug(
105                                 span,
106                                 &format!("unexpected concrete region in borrowck: {:?}", region),
107                             );
108                             region
109                         }
110                     });
111
112                 debug!(
113                     "infer_opaque_types(universal_concrete_type = {:?}, universal_substs = {:?})",
114                     universal_concrete_type, universal_substs
115                 );
116
117                 let remapped_type = infcx.infer_opaque_definition_from_instantiation(
118                     opaque_def_id,
119                     universal_substs,
120                     universal_concrete_type,
121                     span,
122                 );
123                 (
124                     opaque_def_id,
125                     ty::ResolvedOpaqueTy { concrete_type: remapped_type, substs: universal_substs },
126                 )
127             })
128             .collect()
129     }
130
131     /// Map the regions in the type to named regions. This is similar to what
132     /// `infer_opaque_types` does, but can infer any universal region, not only
133     /// ones from the substs for the opaque type. It also doesn't double check
134     /// that the regions produced are in fact equal to the named region they are
135     /// replaced with. This is fine because this function is only to improve the
136     /// region names in error messages.
137     pub(in crate::borrow_check) fn name_regions<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T
138     where
139         T: TypeFoldable<'tcx>,
140     {
141         tcx.fold_regions(&ty, &mut false, |region, _| match *region {
142             ty::ReVar(vid) => {
143                 let upper_bound = self.universal_upper_bound(vid);
144                 self.definitions[upper_bound].external_name.unwrap_or(region)
145             }
146             _ => region,
147         })
148     }
149 }