1 use super::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
2 use super::{FixupError, FixupResult, InferCtxt, Span};
3 use rustc_middle::mir;
4 use rustc_middle::ty::fold::{TypeFolder, TypeVisitor};
5 use rustc_middle::ty::{self, Const, InferConst, Ty, TyCtxt, TypeFoldable};
6 
7 use std::ops::ControlFlow;
8 
9 ///////////////////////////////////////////////////////////////////////////
10 // OPPORTUNISTIC VAR RESOLVER
11 
12 /// The opportunistic resolver can be used at any time. It simply replaces
13 /// type/const variables that have been unified with the things they have
14 /// been unified with (similar to `shallow_resolve`, but deep). This is
15 /// useful for printing messages etc but also required at various
16 /// points for correctness.
17 pub struct OpportunisticVarResolver<'a, 'tcx> {
18     infcx: &'a InferCtxt<'a, 'tcx>,
19 }
20 
21 impl<'a, 'tcx> OpportunisticVarResolver<'a, 'tcx> {
22     #[inline]
new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self23     pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self {
24         OpportunisticVarResolver { infcx }
25     }
26 }
27 
28 impl<'a, 'tcx> TypeFolder<'tcx> for OpportunisticVarResolver<'a, 'tcx> {
tcx<'b>(&'b self) -> TyCtxt<'tcx>29     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
30         self.infcx.tcx
31     }
32 
fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx>33     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
34         if !t.has_infer_types_or_consts() {
35             t // micro-optimize -- if there is nothing in this type that this fold affects...
36         } else {
37             let t = self.infcx.shallow_resolve(t);
38             t.super_fold_with(self)
39         }
40     }
41 
fold_const(&mut self, ct: &'tcx Const<'tcx>) -> &'tcx Const<'tcx>42     fn fold_const(&mut self, ct: &'tcx Const<'tcx>) -> &'tcx Const<'tcx> {
43         if !ct.has_infer_types_or_consts() {
44             ct // micro-optimize -- if there is nothing in this const that this fold affects...
45         } else {
46             let ct = self.infcx.shallow_resolve(ct);
47             ct.super_fold_with(self)
48         }
49     }
50 
fold_mir_const(&mut self, constant: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx>51     fn fold_mir_const(&mut self, constant: mir::ConstantKind<'tcx>) -> mir::ConstantKind<'tcx> {
52         constant.super_fold_with(self)
53     }
54 }
55 
56 /// The opportunistic region resolver opportunistically resolves regions
57 /// variables to the variable with the least variable id. It is used when
58 /// normlizing projections to avoid hitting the recursion limit by creating
59 /// many versions of a predicate for types that in the end have to unify.
60 ///
61 /// If you want to resolve type and const variables as well, call
62 /// [InferCtxt::resolve_vars_if_possible] first.
63 pub struct OpportunisticRegionResolver<'a, 'tcx> {
64     infcx: &'a InferCtxt<'a, 'tcx>,
65 }
66 
67 impl<'a, 'tcx> OpportunisticRegionResolver<'a, 'tcx> {
new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self68     pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self {
69         OpportunisticRegionResolver { infcx }
70     }
71 }
72 
73 impl<'a, 'tcx> TypeFolder<'tcx> for OpportunisticRegionResolver<'a, 'tcx> {
tcx<'b>(&'b self) -> TyCtxt<'tcx>74     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
75         self.infcx.tcx
76     }
77 
fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx>78     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
79         if !t.has_infer_regions() {
80             t // micro-optimize -- if there is nothing in this type that this fold affects...
81         } else {
82             t.super_fold_with(self)
83         }
84     }
85 
fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx>86     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
87         match *r {
88             ty::ReVar(rid) => {
89                 let resolved = self
90                     .infcx
91                     .inner
92                     .borrow_mut()
93                     .unwrap_region_constraints()
94                     .opportunistic_resolve_var(rid);
95                 self.tcx().reuse_or_mk_region(r, ty::ReVar(resolved))
96             }
97             _ => r,
98         }
99     }
100 
fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>101     fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
102         if !ct.has_infer_regions() {
103             ct // micro-optimize -- if there is nothing in this const that this fold affects...
104         } else {
105             ct.super_fold_with(self)
106         }
107     }
108 }
109 
110 ///////////////////////////////////////////////////////////////////////////
111 // UNRESOLVED TYPE FINDER
112 
113 /// The unresolved type **finder** walks a type searching for
114 /// type variables that don't yet have a value. The first unresolved type is stored.
115 /// It does not construct the fully resolved type (which might
116 /// involve some hashing and so forth).
117 pub struct UnresolvedTypeFinder<'a, 'tcx> {
118     infcx: &'a InferCtxt<'a, 'tcx>,
119 }
120 
121 impl<'a, 'tcx> UnresolvedTypeFinder<'a, 'tcx> {
new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self122     pub fn new(infcx: &'a InferCtxt<'a, 'tcx>) -> Self {
123         UnresolvedTypeFinder { infcx }
124     }
125 }
126 
127 impl<'a, 'tcx> TypeVisitor<'tcx> for UnresolvedTypeFinder<'a, 'tcx> {
128     type BreakTy = (Ty<'tcx>, Option<Span>);
129 
tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>>130     fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
131         Some(self.infcx.tcx)
132     }
133 
visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy>134     fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
135         let t = self.infcx.shallow_resolve(t);
136         if t.has_infer_types() {
137             if let ty::Infer(infer_ty) = *t.kind() {
138                 // Since we called `shallow_resolve` above, this must
139                 // be an (as yet...) unresolved inference variable.
140                 let ty_var_span = if let ty::TyVar(ty_vid) = infer_ty {
141                     let mut inner = self.infcx.inner.borrow_mut();
142                     let ty_vars = &inner.type_variables();
143                     if let TypeVariableOrigin {
144                         kind: TypeVariableOriginKind::TypeParameterDefinition(_, _),
145                         span,
146                     } = *ty_vars.var_origin(ty_vid)
147                     {
148                         Some(span)
149                     } else {
150                         None
151                     }
152                 } else {
153                     None
154                 };
155                 ControlFlow::Break((t, ty_var_span))
156             } else {
157                 // Otherwise, visit its contents.
158                 t.super_visit_with(self)
159             }
160         } else {
161             // All type variables in inference types must already be resolved,
162             // - no need to visit the contents, continue visiting.
163             ControlFlow::CONTINUE
164         }
165     }
166 }
167 
168 ///////////////////////////////////////////////////////////////////////////
169 // FULL TYPE RESOLUTION
170 
171 /// Full type resolution replaces all type and region variables with
172 /// their concrete results. If any variable cannot be replaced (never unified, etc)
173 /// then an `Err` result is returned.
fully_resolve<'a, 'tcx, T>(infcx: &InferCtxt<'a, 'tcx>, value: T) -> FixupResult<'tcx, T> where T: TypeFoldable<'tcx>,174 pub fn fully_resolve<'a, 'tcx, T>(infcx: &InferCtxt<'a, 'tcx>, value: T) -> FixupResult<'tcx, T>
175 where
176     T: TypeFoldable<'tcx>,
177 {
178     let mut full_resolver = FullTypeResolver { infcx, err: None };
179     let result = value.fold_with(&mut full_resolver);
180     match full_resolver.err {
181         None => Ok(result),
182         Some(e) => Err(e),
183     }
184 }
185 
186 // N.B. This type is not public because the protocol around checking the
187 // `err` field is not enforceable otherwise.
188 struct FullTypeResolver<'a, 'tcx> {
189     infcx: &'a InferCtxt<'a, 'tcx>,
190     err: Option<FixupError<'tcx>>,
191 }
192 
193 impl<'a, 'tcx> TypeFolder<'tcx> for FullTypeResolver<'a, 'tcx> {
tcx<'b>(&'b self) -> TyCtxt<'tcx>194     fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
195         self.infcx.tcx
196     }
197 
fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx>198     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
199         if !t.needs_infer() {
200             t // micro-optimize -- if there is nothing in this type that this fold affects...
201         } else {
202             let t = self.infcx.shallow_resolve(t);
203             match *t.kind() {
204                 ty::Infer(ty::TyVar(vid)) => {
205                     self.err = Some(FixupError::UnresolvedTy(vid));
206                     self.tcx().ty_error()
207                 }
208                 ty::Infer(ty::IntVar(vid)) => {
209                     self.err = Some(FixupError::UnresolvedIntTy(vid));
210                     self.tcx().ty_error()
211                 }
212                 ty::Infer(ty::FloatVar(vid)) => {
213                     self.err = Some(FixupError::UnresolvedFloatTy(vid));
214                     self.tcx().ty_error()
215                 }
216                 ty::Infer(_) => {
217                     bug!("Unexpected type in full type resolver: {:?}", t);
218                 }
219                 _ => t.super_fold_with(self),
220             }
221         }
222     }
223 
fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx>224     fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
225         match *r {
226             ty::ReVar(rid) => self
227                 .infcx
228                 .lexical_region_resolutions
229                 .borrow()
230                 .as_ref()
231                 .expect("region resolution not performed")
232                 .resolve_var(rid),
233             _ => r,
234         }
235     }
236 
fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx>237     fn fold_const(&mut self, c: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
238         if !c.needs_infer() {
239             c // micro-optimize -- if there is nothing in this const that this fold affects...
240         } else {
241             let c = self.infcx.shallow_resolve(c);
242             match c.val {
243                 ty::ConstKind::Infer(InferConst::Var(vid)) => {
244                     self.err = Some(FixupError::UnresolvedConst(vid));
245                     return self.tcx().const_error(c.ty);
246                 }
247                 ty::ConstKind::Infer(InferConst::Fresh(_)) => {
248                     bug!("Unexpected const in full const resolver: {:?}", c);
249                 }
250                 _ => {}
251             }
252             c.super_fold_with(self)
253         }
254     }
255 }
256