]>
Commit | Line | Data |
---|---|---|
3c0e092e XL |
1 | use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; |
2 | use crate::infer::{InferCtxt, InferOk}; | |
3 | use crate::traits; | |
4 | use rustc_data_structures::sync::Lrc; | |
94222f64 XL |
5 | use rustc_data_structures::vec_map::VecMap; |
6 | use rustc_hir as hir; | |
3c0e092e XL |
7 | use rustc_hir::def_id::LocalDefId; |
8 | use rustc_middle::ty::fold::BottomUpFolder; | |
9 | use rustc_middle::ty::subst::{GenericArgKind, Subst}; | |
10 | use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable, TypeVisitor}; | |
94222f64 XL |
11 | use rustc_span::Span; |
12 | ||
3c0e092e XL |
13 | use std::ops::ControlFlow; |
14 | ||
94222f64 XL |
15 | pub type OpaqueTypeMap<'tcx> = VecMap<OpaqueTypeKey<'tcx>, OpaqueTypeDecl<'tcx>>; |
16 | ||
17 | /// Information about the opaque types whose values we | |
18 | /// are inferring in this function (these are the `impl Trait` that | |
19 | /// appear in the return type). | |
20 | #[derive(Copy, Clone, Debug)] | |
21 | pub struct OpaqueTypeDecl<'tcx> { | |
22 | /// The opaque type (`ty::Opaque`) for this declaration. | |
23 | pub opaque_type: Ty<'tcx>, | |
24 | ||
25 | /// The span of this particular definition of the opaque type. So | |
26 | /// for example: | |
27 | /// | |
28 | /// ```ignore (incomplete snippet) | |
29 | /// type Foo = impl Baz; | |
30 | /// fn bar() -> Foo { | |
31 | /// // ^^^ This is the span we are looking for! | |
32 | /// } | |
33 | /// ``` | |
34 | /// | |
35 | /// In cases where the fn returns `(impl Trait, impl Trait)` or | |
36 | /// other such combinations, the result is currently | |
37 | /// over-approximated, but better than nothing. | |
38 | pub definition_span: Span, | |
39 | ||
40 | /// The type variable that represents the value of the opaque type | |
41 | /// that we require. In other words, after we compile this function, | |
42 | /// we will be created a constraint like: | |
43 | /// | |
44 | /// Foo<'a, T> = ?C | |
45 | /// | |
46 | /// where `?C` is the value of this type variable. =) It may | |
47 | /// naturally refer to the type and lifetime parameters in scope | |
48 | /// in this function, though ultimately it should only reference | |
49 | /// those that are arguments to `Foo` in the constraint above. (In | |
50 | /// other words, `?C` should not include `'b`, even though it's a | |
51 | /// lifetime parameter on `foo`.) | |
52 | pub concrete_ty: Ty<'tcx>, | |
53 | ||
54 | /// The origin of the opaque type. | |
55 | pub origin: hir::OpaqueTyOrigin, | |
56 | } | |
3c0e092e XL |
57 | |
58 | impl<'a, 'tcx> InferCtxt<'a, 'tcx> { | |
59 | /// Replaces all opaque types in `value` with fresh inference variables | |
60 | /// and creates appropriate obligations. For example, given the input: | |
61 | /// | |
62 | /// impl Iterator<Item = impl Debug> | |
63 | /// | |
64 | /// this method would create two type variables, `?0` and `?1`. It would | |
65 | /// return the type `?0` but also the obligations: | |
66 | /// | |
67 | /// ?0: Iterator<Item = ?1> | |
68 | /// ?1: Debug | |
69 | /// | |
70 | /// Moreover, it returns an `OpaqueTypeMap` that would map `?0` to | |
71 | /// info about the `impl Iterator<..>` type and `?1` to info about | |
72 | /// the `impl Debug` type. | |
73 | /// | |
74 | /// # Parameters | |
75 | /// | |
76 | /// - `parent_def_id` -- the `DefId` of the function in which the opaque type | |
77 | /// is defined | |
78 | /// - `body_id` -- the body-id with which the resulting obligations should | |
79 | /// be associated | |
80 | /// - `param_env` -- the in-scope parameter environment to be used for | |
81 | /// obligations | |
82 | /// - `value` -- the value within which we are instantiating opaque types | |
83 | /// - `value_span` -- the span where the value came from, used in error reporting | |
84 | pub fn instantiate_opaque_types<T: TypeFoldable<'tcx>>( | |
85 | &self, | |
86 | body_id: hir::HirId, | |
87 | param_env: ty::ParamEnv<'tcx>, | |
88 | value: T, | |
89 | value_span: Span, | |
90 | ) -> InferOk<'tcx, T> { | |
91 | debug!( | |
92 | "instantiate_opaque_types(value={:?}, body_id={:?}, \ | |
93 | param_env={:?}, value_span={:?})", | |
94 | value, body_id, param_env, value_span, | |
95 | ); | |
96 | let mut instantiator = | |
97 | Instantiator { infcx: self, body_id, param_env, value_span, obligations: vec![] }; | |
98 | let value = instantiator.instantiate_opaque_types_in_map(value); | |
99 | InferOk { value, obligations: instantiator.obligations } | |
100 | } | |
101 | ||
102 | /// Given the map `opaque_types` containing the opaque | |
103 | /// `impl Trait` types whose underlying, hidden types are being | |
104 | /// inferred, this method adds constraints to the regions | |
105 | /// appearing in those underlying hidden types to ensure that they | |
106 | /// at least do not refer to random scopes within the current | |
107 | /// function. These constraints are not (quite) sufficient to | |
108 | /// guarantee that the regions are actually legal values; that | |
109 | /// final condition is imposed after region inference is done. | |
110 | /// | |
111 | /// # The Problem | |
112 | /// | |
113 | /// Let's work through an example to explain how it works. Assume | |
114 | /// the current function is as follows: | |
115 | /// | |
116 | /// ```text | |
117 | /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>) | |
118 | /// ``` | |
119 | /// | |
120 | /// Here, we have two `impl Trait` types whose values are being | |
121 | /// inferred (the `impl Bar<'a>` and the `impl | |
122 | /// Bar<'b>`). Conceptually, this is sugar for a setup where we | |
123 | /// define underlying opaque types (`Foo1`, `Foo2`) and then, in | |
124 | /// the return type of `foo`, we *reference* those definitions: | |
125 | /// | |
126 | /// ```text | |
127 | /// type Foo1<'x> = impl Bar<'x>; | |
128 | /// type Foo2<'x> = impl Bar<'x>; | |
129 | /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. } | |
130 | /// // ^^^^ ^^ | |
131 | /// // | | | |
132 | /// // | substs | |
133 | /// // def_id | |
134 | /// ``` | |
135 | /// | |
136 | /// As indicating in the comments above, each of those references | |
137 | /// is (in the compiler) basically a substitution (`substs`) | |
138 | /// applied to the type of a suitable `def_id` (which identifies | |
139 | /// `Foo1` or `Foo2`). | |
140 | /// | |
141 | /// Now, at this point in compilation, what we have done is to | |
142 | /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with | |
143 | /// fresh inference variables C1 and C2. We wish to use the values | |
144 | /// of these variables to infer the underlying types of `Foo1` and | |
145 | /// `Foo2`. That is, this gives rise to higher-order (pattern) unification | |
146 | /// constraints like: | |
147 | /// | |
148 | /// ```text | |
149 | /// for<'a> (Foo1<'a> = C1) | |
150 | /// for<'b> (Foo1<'b> = C2) | |
151 | /// ``` | |
152 | /// | |
153 | /// For these equation to be satisfiable, the types `C1` and `C2` | |
154 | /// can only refer to a limited set of regions. For example, `C1` | |
155 | /// can only refer to `'static` and `'a`, and `C2` can only refer | |
156 | /// to `'static` and `'b`. The job of this function is to impose that | |
157 | /// constraint. | |
158 | /// | |
159 | /// Up to this point, C1 and C2 are basically just random type | |
160 | /// inference variables, and hence they may contain arbitrary | |
161 | /// regions. In fact, it is fairly likely that they do! Consider | |
162 | /// this possible definition of `foo`: | |
163 | /// | |
164 | /// ```text | |
165 | /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) { | |
166 | /// (&*x, &*y) | |
167 | /// } | |
168 | /// ``` | |
169 | /// | |
170 | /// Here, the values for the concrete types of the two impl | |
171 | /// traits will include inference variables: | |
172 | /// | |
173 | /// ```text | |
174 | /// &'0 i32 | |
175 | /// &'1 i32 | |
176 | /// ``` | |
177 | /// | |
178 | /// Ordinarily, the subtyping rules would ensure that these are | |
179 | /// sufficiently large. But since `impl Bar<'a>` isn't a specific | |
180 | /// type per se, we don't get such constraints by default. This | |
181 | /// is where this function comes into play. It adds extra | |
182 | /// constraints to ensure that all the regions which appear in the | |
183 | /// inferred type are regions that could validly appear. | |
184 | /// | |
185 | /// This is actually a bit of a tricky constraint in general. We | |
186 | /// want to say that each variable (e.g., `'0`) can only take on | |
187 | /// values that were supplied as arguments to the opaque type | |
188 | /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in | |
189 | /// scope. We don't have a constraint quite of this kind in the current | |
190 | /// region checker. | |
191 | /// | |
192 | /// # The Solution | |
193 | /// | |
194 | /// We generally prefer to make `<=` constraints, since they | |
195 | /// integrate best into the region solver. To do that, we find the | |
196 | /// "minimum" of all the arguments that appear in the substs: that | |
197 | /// is, some region which is less than all the others. In the case | |
198 | /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after | |
199 | /// all). Then we apply that as a least bound to the variables | |
200 | /// (e.g., `'a <= '0`). | |
201 | /// | |
202 | /// In some cases, there is no minimum. Consider this example: | |
203 | /// | |
204 | /// ```text | |
205 | /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... } | |
206 | /// ``` | |
207 | /// | |
208 | /// Here we would report a more complex "in constraint", like `'r | |
209 | /// in ['a, 'b, 'static]` (where `'r` is some region appearing in | |
210 | /// the hidden type). | |
211 | /// | |
212 | /// # Constrain regions, not the hidden concrete type | |
213 | /// | |
214 | /// Note that generating constraints on each region `Rc` is *not* | |
215 | /// the same as generating an outlives constraint on `Tc` iself. | |
216 | /// For example, if we had a function like this: | |
217 | /// | |
218 | /// ```rust | |
219 | /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> { | |
220 | /// (x, y) | |
221 | /// } | |
222 | /// | |
223 | /// // Equivalent to: | |
224 | /// type FooReturn<'a, T> = impl Foo<'a>; | |
225 | /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. } | |
226 | /// ``` | |
227 | /// | |
228 | /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0` | |
229 | /// is an inference variable). If we generated a constraint that | |
230 | /// `Tc: 'a`, then this would incorrectly require that `T: 'a` -- | |
231 | /// but this is not necessary, because the opaque type we | |
232 | /// create will be allowed to reference `T`. So we only generate a | |
233 | /// constraint that `'0: 'a`. | |
234 | /// | |
235 | /// # The `free_region_relations` parameter | |
236 | /// | |
237 | /// The `free_region_relations` argument is used to find the | |
238 | /// "minimum" of the regions supplied to a given opaque type. | |
239 | /// It must be a relation that can answer whether `'a <= 'b`, | |
240 | /// where `'a` and `'b` are regions that appear in the "substs" | |
241 | /// for the opaque type references (the `<'a>` in `Foo1<'a>`). | |
242 | /// | |
243 | /// Note that we do not impose the constraints based on the | |
244 | /// generic regions from the `Foo1` definition (e.g., `'x`). This | |
245 | /// is because the constraints we are imposing here is basically | |
246 | /// the concern of the one generating the constraining type C1, | |
247 | /// which is the current function. It also means that we can | |
248 | /// take "implied bounds" into account in some cases: | |
249 | /// | |
250 | /// ```text | |
251 | /// trait SomeTrait<'a, 'b> { } | |
252 | /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. } | |
253 | /// ``` | |
254 | /// | |
255 | /// Here, the fact that `'b: 'a` is known only because of the | |
256 | /// implied bounds from the `&'a &'b u32` parameter, and is not | |
257 | /// "inherent" to the opaque type definition. | |
258 | /// | |
259 | /// # Parameters | |
260 | /// | |
261 | /// - `opaque_types` -- the map produced by `instantiate_opaque_types` | |
262 | /// - `free_region_relations` -- something that can be used to relate | |
263 | /// the free regions (`'a`) that appear in the impl trait. | |
264 | #[instrument(level = "debug", skip(self))] | |
265 | pub fn constrain_opaque_type( | |
266 | &self, | |
267 | opaque_type_key: OpaqueTypeKey<'tcx>, | |
268 | opaque_defn: &OpaqueTypeDecl<'tcx>, | |
269 | ) { | |
270 | let def_id = opaque_type_key.def_id; | |
271 | ||
272 | let tcx = self.tcx; | |
273 | ||
274 | let concrete_ty = self.resolve_vars_if_possible(opaque_defn.concrete_ty); | |
275 | ||
276 | debug!(?concrete_ty); | |
277 | ||
278 | let first_own_region = match opaque_defn.origin { | |
a2a8927a | 279 | hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => { |
3c0e092e XL |
280 | // We lower |
281 | // | |
282 | // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm> | |
283 | // | |
284 | // into | |
285 | // | |
286 | // type foo::<'p0..'pn>::Foo<'q0..'qm> | |
287 | // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>. | |
288 | // | |
289 | // For these types we only iterate over `'l0..lm` below. | |
290 | tcx.generics_of(def_id).parent_count | |
291 | } | |
292 | // These opaque type inherit all lifetime parameters from their | |
293 | // parent, so we have to check them all. | |
294 | hir::OpaqueTyOrigin::TyAlias => 0, | |
295 | }; | |
296 | ||
297 | // For a case like `impl Foo<'a, 'b>`, we would generate a constraint | |
298 | // `'r in ['a, 'b, 'static]` for each region `'r` that appears in the | |
299 | // hidden type (i.e., it must be equal to `'a`, `'b`, or `'static`). | |
300 | // | |
301 | // `conflict1` and `conflict2` are the two region bounds that we | |
302 | // detected which were unrelated. They are used for diagnostics. | |
303 | ||
304 | // Create the set of choice regions: each region in the hidden | |
305 | // type can be equal to any of the region parameters of the | |
306 | // opaque type definition. | |
307 | let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new( | |
308 | opaque_type_key.substs[first_own_region..] | |
309 | .iter() | |
310 | .filter_map(|arg| match arg.unpack() { | |
311 | GenericArgKind::Lifetime(r) => Some(r), | |
312 | GenericArgKind::Type(_) | GenericArgKind::Const(_) => None, | |
313 | }) | |
314 | .chain(std::iter::once(self.tcx.lifetimes.re_static)) | |
315 | .collect(), | |
316 | ); | |
317 | ||
318 | concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor { | |
319 | tcx: self.tcx, | |
320 | op: |r| { | |
321 | self.member_constraint( | |
322 | opaque_type_key.def_id, | |
323 | opaque_defn.definition_span, | |
324 | concrete_ty, | |
325 | r, | |
326 | &choice_regions, | |
327 | ) | |
328 | }, | |
329 | }); | |
330 | } | |
331 | } | |
332 | ||
333 | // Visitor that requires that (almost) all regions in the type visited outlive | |
334 | // `least_region`. We cannot use `push_outlives_components` because regions in | |
335 | // closure signatures are not included in their outlives components. We need to | |
336 | // ensure all regions outlive the given bound so that we don't end up with, | |
337 | // say, `ReVar` appearing in a return type and causing ICEs when other | |
338 | // functions end up with region constraints involving regions from other | |
339 | // functions. | |
340 | // | |
341 | // We also cannot use `for_each_free_region` because for closures it includes | |
342 | // the regions parameters from the enclosing item. | |
343 | // | |
344 | // We ignore any type parameters because impl trait values are assumed to | |
345 | // capture all the in-scope type parameters. | |
346 | struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP> { | |
347 | tcx: TyCtxt<'tcx>, | |
348 | op: OP, | |
349 | } | |
350 | ||
351 | impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP> | |
352 | where | |
353 | OP: FnMut(ty::Region<'tcx>), | |
354 | { | |
355 | fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> { | |
356 | Some(self.tcx) | |
357 | } | |
358 | ||
359 | fn visit_binder<T: TypeFoldable<'tcx>>( | |
360 | &mut self, | |
361 | t: &ty::Binder<'tcx, T>, | |
362 | ) -> ControlFlow<Self::BreakTy> { | |
363 | t.as_ref().skip_binder().visit_with(self); | |
364 | ControlFlow::CONTINUE | |
365 | } | |
366 | ||
367 | fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> { | |
368 | match *r { | |
369 | // ignore bound regions, keep visiting | |
370 | ty::ReLateBound(_, _) => ControlFlow::CONTINUE, | |
371 | _ => { | |
372 | (self.op)(r); | |
373 | ControlFlow::CONTINUE | |
374 | } | |
375 | } | |
376 | } | |
377 | ||
378 | fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> { | |
379 | // We're only interested in types involving regions | |
380 | if !ty.flags().intersects(ty::TypeFlags::HAS_POTENTIAL_FREE_REGIONS) { | |
381 | return ControlFlow::CONTINUE; | |
382 | } | |
383 | ||
384 | match ty.kind() { | |
385 | ty::Closure(_, ref substs) => { | |
386 | // Skip lifetime parameters of the enclosing item(s) | |
387 | ||
388 | substs.as_closure().tupled_upvars_ty().visit_with(self); | |
389 | substs.as_closure().sig_as_fn_ptr_ty().visit_with(self); | |
390 | } | |
391 | ||
392 | ty::Generator(_, ref substs, _) => { | |
393 | // Skip lifetime parameters of the enclosing item(s) | |
394 | // Also skip the witness type, because that has no free regions. | |
395 | ||
396 | substs.as_generator().tupled_upvars_ty().visit_with(self); | |
397 | substs.as_generator().return_ty().visit_with(self); | |
398 | substs.as_generator().yield_ty().visit_with(self); | |
399 | substs.as_generator().resume_ty().visit_with(self); | |
400 | } | |
401 | _ => { | |
402 | ty.super_visit_with(self); | |
403 | } | |
404 | } | |
405 | ||
406 | ControlFlow::CONTINUE | |
407 | } | |
408 | } | |
409 | ||
410 | struct Instantiator<'a, 'tcx> { | |
411 | infcx: &'a InferCtxt<'a, 'tcx>, | |
412 | body_id: hir::HirId, | |
413 | param_env: ty::ParamEnv<'tcx>, | |
414 | value_span: Span, | |
415 | obligations: Vec<traits::PredicateObligation<'tcx>>, | |
416 | } | |
417 | ||
418 | impl<'a, 'tcx> Instantiator<'a, 'tcx> { | |
419 | fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T { | |
420 | let tcx = self.infcx.tcx; | |
421 | value.fold_with(&mut BottomUpFolder { | |
422 | tcx, | |
423 | ty_op: |ty| { | |
424 | if ty.references_error() { | |
425 | return tcx.ty_error(); | |
426 | } else if let ty::Opaque(def_id, substs) = ty.kind() { | |
427 | // Check that this is `impl Trait` type is | |
428 | // declared by `parent_def_id` -- i.e., one whose | |
429 | // value we are inferring. At present, this is | |
430 | // always true during the first phase of | |
431 | // type-check, but not always true later on during | |
432 | // NLL. Once we support named opaque types more fully, | |
433 | // this same scenario will be able to arise during all phases. | |
434 | // | |
435 | // Here is an example using type alias `impl Trait` | |
436 | // that indicates the distinction we are checking for: | |
437 | // | |
438 | // ```rust | |
439 | // mod a { | |
440 | // pub type Foo = impl Iterator; | |
441 | // pub fn make_foo() -> Foo { .. } | |
442 | // } | |
443 | // | |
444 | // mod b { | |
445 | // fn foo() -> a::Foo { a::make_foo() } | |
446 | // } | |
447 | // ``` | |
448 | // | |
449 | // Here, the return type of `foo` references an | |
450 | // `Opaque` indeed, but not one whose value is | |
451 | // presently being inferred. You can get into a | |
452 | // similar situation with closure return types | |
453 | // today: | |
454 | // | |
455 | // ```rust | |
456 | // fn foo() -> impl Iterator { .. } | |
457 | // fn bar() { | |
458 | // let x = || foo(); // returns the Opaque assoc with `foo` | |
459 | // } | |
460 | // ``` | |
461 | if let Some(def_id) = def_id.as_local() { | |
462 | let opaque_hir_id = tcx.hir().local_def_id_to_hir_id(def_id); | |
463 | let parent_def_id = self.infcx.defining_use_anchor; | |
a2a8927a XL |
464 | let item_kind = &tcx.hir().expect_item(def_id).kind; |
465 | let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) = item_kind else { | |
466 | span_bug!( | |
467 | self.value_span, | |
468 | "weird opaque type: {:#?}, {:#?}", | |
469 | ty.kind(), | |
470 | item_kind | |
471 | ) | |
472 | }; | |
473 | let in_definition_scope = match *origin { | |
474 | // Async `impl Trait` | |
475 | hir::OpaqueTyOrigin::AsyncFn(parent) => parent == parent_def_id, | |
476 | // Anonymous `impl Trait` | |
477 | hir::OpaqueTyOrigin::FnReturn(parent) => parent == parent_def_id, | |
478 | // Named `type Foo = impl Bar;` | |
479 | hir::OpaqueTyOrigin::TyAlias => { | |
480 | may_define_opaque_type(tcx, parent_def_id, opaque_hir_id) | |
481 | } | |
3c0e092e | 482 | }; |
3c0e092e XL |
483 | if in_definition_scope { |
484 | let opaque_type_key = | |
485 | OpaqueTypeKey { def_id: def_id.to_def_id(), substs }; | |
a2a8927a | 486 | return self.fold_opaque_ty(ty, opaque_type_key, *origin); |
3c0e092e XL |
487 | } |
488 | ||
489 | debug!( | |
490 | "instantiate_opaque_types_in_map: \ | |
491 | encountered opaque outside its definition scope \ | |
492 | def_id={:?}", | |
493 | def_id, | |
494 | ); | |
495 | } | |
496 | } | |
497 | ||
498 | ty | |
499 | }, | |
500 | lt_op: |lt| lt, | |
501 | ct_op: |ct| ct, | |
502 | }) | |
503 | } | |
504 | ||
505 | #[instrument(skip(self), level = "debug")] | |
506 | fn fold_opaque_ty( | |
507 | &mut self, | |
508 | ty: Ty<'tcx>, | |
509 | opaque_type_key: OpaqueTypeKey<'tcx>, | |
510 | origin: hir::OpaqueTyOrigin, | |
511 | ) -> Ty<'tcx> { | |
512 | let infcx = self.infcx; | |
513 | let tcx = infcx.tcx; | |
514 | let OpaqueTypeKey { def_id, substs } = opaque_type_key; | |
515 | ||
516 | // Use the same type variable if the exact same opaque type appears more | |
517 | // than once in the return type (e.g., if it's passed to a type alias). | |
518 | if let Some(opaque_defn) = infcx.inner.borrow().opaque_types.get(&opaque_type_key) { | |
519 | debug!("re-using cached concrete type {:?}", opaque_defn.concrete_ty.kind()); | |
520 | return opaque_defn.concrete_ty; | |
521 | } | |
522 | ||
523 | let ty_var = infcx.next_ty_var(TypeVariableOrigin { | |
524 | kind: TypeVariableOriginKind::TypeInference, | |
525 | span: self.value_span, | |
526 | }); | |
527 | ||
528 | // Ideally, we'd get the span where *this specific `ty` came | |
529 | // from*, but right now we just use the span from the overall | |
530 | // value being folded. In simple cases like `-> impl Foo`, | |
531 | // these are the same span, but not in cases like `-> (impl | |
532 | // Foo, impl Bar)`. | |
533 | let definition_span = self.value_span; | |
534 | ||
535 | { | |
536 | let mut infcx = self.infcx.inner.borrow_mut(); | |
537 | infcx.opaque_types.insert( | |
538 | OpaqueTypeKey { def_id, substs }, | |
539 | OpaqueTypeDecl { opaque_type: ty, definition_span, concrete_ty: ty_var, origin }, | |
540 | ); | |
541 | infcx.opaque_types_vars.insert(ty_var, ty); | |
542 | } | |
543 | ||
544 | debug!("generated new type inference var {:?}", ty_var.kind()); | |
545 | ||
546 | let item_bounds = tcx.explicit_item_bounds(def_id); | |
547 | ||
548 | self.obligations.reserve(item_bounds.len()); | |
549 | for (predicate, _) in item_bounds { | |
550 | debug!(?predicate); | |
551 | let predicate = predicate.subst(tcx, substs); | |
552 | debug!(?predicate); | |
553 | ||
554 | // We can't normalize associated types from `rustc_infer`, but we can eagerly register inference variables for them. | |
555 | let predicate = predicate.fold_with(&mut BottomUpFolder { | |
556 | tcx, | |
557 | ty_op: |ty| match ty.kind() { | |
558 | ty::Projection(projection_ty) => infcx.infer_projection( | |
559 | self.param_env, | |
560 | *projection_ty, | |
561 | traits::ObligationCause::misc(self.value_span, self.body_id), | |
562 | 0, | |
563 | &mut self.obligations, | |
564 | ), | |
565 | _ => ty, | |
566 | }, | |
567 | lt_op: |lt| lt, | |
568 | ct_op: |ct| ct, | |
569 | }); | |
570 | debug!(?predicate); | |
571 | ||
572 | if let ty::PredicateKind::Projection(projection) = predicate.kind().skip_binder() { | |
573 | if projection.ty.references_error() { | |
574 | // No point on adding these obligations since there's a type error involved. | |
575 | return tcx.ty_error(); | |
576 | } | |
577 | } | |
578 | // Change the predicate to refer to the type variable, | |
579 | // which will be the concrete type instead of the opaque type. | |
580 | // This also instantiates nested instances of `impl Trait`. | |
581 | let predicate = self.instantiate_opaque_types_in_map(predicate); | |
582 | ||
583 | let cause = | |
584 | traits::ObligationCause::new(self.value_span, self.body_id, traits::OpaqueType); | |
585 | ||
586 | // Require that the predicate holds for the concrete type. | |
587 | debug!(?predicate); | |
588 | self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate)); | |
589 | } | |
590 | ||
591 | ty_var | |
592 | } | |
593 | } | |
594 | ||
595 | /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`. | |
596 | /// | |
597 | /// Example: | |
598 | /// ```rust | |
599 | /// pub mod foo { | |
600 | /// pub mod bar { | |
601 | /// pub trait Bar { .. } | |
602 | /// | |
603 | /// pub type Baz = impl Bar; | |
604 | /// | |
605 | /// fn f1() -> Baz { .. } | |
606 | /// } | |
607 | /// | |
608 | /// fn f2() -> bar::Baz { .. } | |
609 | /// } | |
610 | /// ``` | |
611 | /// | |
612 | /// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`), | |
613 | /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`. | |
614 | /// For the above example, this function returns `true` for `f1` and `false` for `f2`. | |
615 | fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hir::HirId) -> bool { | |
616 | let mut hir_id = tcx.hir().local_def_id_to_hir_id(def_id); | |
617 | ||
618 | // Named opaque types can be defined by any siblings or children of siblings. | |
619 | let scope = tcx.hir().get_defining_scope(opaque_hir_id); | |
620 | // We walk up the node tree until we hit the root or the scope of the opaque type. | |
621 | while hir_id != scope && hir_id != hir::CRATE_HIR_ID { | |
622 | hir_id = tcx.hir().get_parent_item(hir_id); | |
623 | } | |
624 | // Syntactically, we are allowed to define the concrete type if: | |
625 | let res = hir_id == scope; | |
626 | trace!( | |
627 | "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}", | |
628 | tcx.hir().find(hir_id), | |
629 | tcx.hir().get(opaque_hir_id), | |
630 | res | |
631 | ); | |
632 | res | |
633 | } |