]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_trait_selection/src/opaque_types.rs
New upstream version 1.53.0+dfsg1
[rustc.git] / compiler / rustc_trait_selection / src / opaque_types.rs
CommitLineData
ba9703b0 1use crate::infer::InferCtxtExt as _;
9fa01778 2use crate::traits::{self, PredicateObligation};
dc9dc135
XL
3use rustc_data_structures::fx::FxHashMap;
4use rustc_data_structures::sync::Lrc;
dfeec247 5use rustc_hir as hir;
f9f354fc 6use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId};
dfeec247 7use rustc_hir::Node;
ba9703b0 8use rustc_infer::infer::error_reporting::unexpected_hidden_region_diagnostic;
f9f354fc 9use rustc_infer::infer::free_regions::FreeRegionRelations;
ba9703b0
XL
10use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
11use rustc_infer::infer::{self, InferCtxt, InferOk};
12use rustc_middle::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor};
29967ef6 13use rustc_middle::ty::subst::{GenericArg, GenericArgKind, InternalSubsts, Subst, SubstsRef};
f035d41b 14use rustc_middle::ty::{self, Ty, TyCtxt};
dfeec247 15use rustc_span::Span;
60c5eb7d 16
29967ef6
XL
17use std::ops::ControlFlow;
18
b7449926 19pub type OpaqueTypeMap<'tcx> = DefIdMap<OpaqueTypeDecl<'tcx>>;
ff7c6d11 20
416331ca 21/// Information about the opaque types whose values we
ff7c6d11
XL
22/// are inferring in this function (these are the `impl Trait` that
23/// appear in the return type).
24#[derive(Copy, Clone, Debug)]
b7449926 25pub struct OpaqueTypeDecl<'tcx> {
60c5eb7d
XL
26 /// The opaque type (`ty::Opaque`) for this declaration.
27 pub opaque_type: Ty<'tcx>,
28
416331ca 29 /// The substitutions that we apply to the opaque type that this
ff7c6d11
XL
30 /// `impl Trait` desugars to. e.g., if:
31 ///
32 /// fn foo<'a, 'b, T>() -> impl Trait<'a>
33 ///
34 /// winds up desugared to:
35 ///
416331ca 36 /// type Foo<'x, X> = impl Trait<'x>
ff7c6d11
XL
37 /// fn foo<'a, 'b, T>() -> Foo<'a, T>
38 ///
39 /// then `substs` would be `['a, T]`.
532ac7d7 40 pub substs: SubstsRef<'tcx>,
ff7c6d11 41
29967ef6 42 /// The span of this particular definition of the opaque type. So
dc9dc135
XL
43 /// for example:
44 ///
29967ef6 45 /// ```ignore (incomplete snippet)
416331ca 46 /// type Foo = impl Baz;
dc9dc135 47 /// fn bar() -> Foo {
29967ef6 48 /// // ^^^ This is the span we are looking for!
dc9dc135
XL
49 /// ```
50 ///
51 /// In cases where the fn returns `(impl Trait, impl Trait)` or
52 /// other such combinations, the result is currently
53 /// over-approximated, but better than nothing.
54 pub definition_span: Span,
55
416331ca 56 /// The type variable that represents the value of the opaque type
ff7c6d11
XL
57 /// that we require. In other words, after we compile this function,
58 /// we will be created a constraint like:
59 ///
60 /// Foo<'a, T> = ?C
61 ///
62 /// where `?C` is the value of this type variable. =) It may
63 /// naturally refer to the type and lifetime parameters in scope
64 /// in this function, though ultimately it should only reference
65 /// those that are arguments to `Foo` in the constraint above. (In
66 /// other words, `?C` should not include `'b`, even though it's a
67 /// lifetime parameter on `foo`.)
68 pub concrete_ty: Ty<'tcx>,
69
9fa01778 70 /// Returns `true` if the `impl Trait` bounds include region bounds.
ff7c6d11
XL
71 /// For example, this would be true for:
72 ///
73 /// fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
74 ///
75 /// but false for:
76 ///
77 /// fn foo<'c>() -> impl Trait<'c>
78 ///
79 /// unless `Trait` was declared like:
80 ///
81 /// trait Trait<'c>: 'c
82 ///
83 /// in which case it would be true.
84 ///
85 /// This is used during regionck to decide whether we need to
86 /// impose any additional constraints to ensure that region
87 /// variables in `concrete_ty` wind up being constrained to
88 /// something from `substs` (or, at minimum, things that outlive
89 /// the fn body). (Ultimately, writeback is responsible for this
90 /// check.)
91 pub has_required_region_bounds: bool,
532ac7d7 92
416331ca
XL
93 /// The origin of the opaque type.
94 pub origin: hir::OpaqueTyOrigin,
ff7c6d11
XL
95}
96
74b04a01
XL
97/// Whether member constraints should be generated for all opaque types
98pub enum GenerateMemberConstraints {
99 /// The default, used by typeck
100 WhenRequired,
101 /// The borrow checker needs member constraints in any case where we don't
102 /// have a `'static` bound. This is because the borrow checker has more
103 /// flexibility in the values of regions. For example, given `f<'a, 'b>`
104 /// the borrow checker can have an inference variable outlive `'a` and `'b`,
105 /// but not be equal to `'static`.
106 IfNoStaticBound,
107}
108
ba9703b0
XL
109pub trait InferCtxtExt<'tcx> {
110 fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
111 &self,
f035d41b 112 parent_def_id: LocalDefId,
ba9703b0
XL
113 body_id: hir::HirId,
114 param_env: ty::ParamEnv<'tcx>,
fc512014 115 value: T,
ba9703b0
XL
116 value_span: Span,
117 ) -> InferOk<'tcx, (T, OpaqueTypeMap<'tcx>)>;
118
119 fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(
120 &self,
121 opaque_types: &OpaqueTypeMap<'tcx>,
122 free_region_relations: &FRR,
123 );
124
125 fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
126 &self,
127 def_id: DefId,
128 opaque_defn: &OpaqueTypeDecl<'tcx>,
129 mode: GenerateMemberConstraints,
130 free_region_relations: &FRR,
131 );
132
133 /*private*/
134 fn generate_member_constraint(
135 &self,
136 concrete_ty: Ty<'tcx>,
ba9703b0
XL
137 opaque_defn: &OpaqueTypeDecl<'tcx>,
138 opaque_type_def_id: DefId,
f035d41b 139 first_own_region_index: usize,
ba9703b0
XL
140 );
141
142 /*private*/
143 fn member_constraint_feature_gate(
144 &self,
145 opaque_defn: &OpaqueTypeDecl<'tcx>,
146 opaque_type_def_id: DefId,
147 conflict1: ty::Region<'tcx>,
148 conflict2: ty::Region<'tcx>,
149 ) -> bool;
150
151 fn infer_opaque_definition_from_instantiation(
152 &self,
153 def_id: DefId,
154 substs: SubstsRef<'tcx>,
155 instantiated_ty: Ty<'tcx>,
156 span: Span,
157 ) -> Ty<'tcx>;
158}
159
160impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
9fa01778 161 /// Replaces all opaque types in `value` with fresh inference variables
ff7c6d11
XL
162 /// and creates appropriate obligations. For example, given the input:
163 ///
164 /// impl Iterator<Item = impl Debug>
165 ///
166 /// this method would create two type variables, `?0` and `?1`. It would
167 /// return the type `?0` but also the obligations:
168 ///
169 /// ?0: Iterator<Item = ?1>
170 /// ?1: Debug
171 ///
b7449926 172 /// Moreover, it returns a `OpaqueTypeMap` that would map `?0` to
ff7c6d11
XL
173 /// info about the `impl Iterator<..>` type and `?1` to info about
174 /// the `impl Debug` type.
175 ///
176 /// # Parameters
177 ///
9fa01778 178 /// - `parent_def_id` -- the `DefId` of the function in which the opaque type
0bf4aa26 179 /// is defined
ff7c6d11
XL
180 /// - `body_id` -- the body-id with which the resulting obligations should
181 /// be associated
182 /// - `param_env` -- the in-scope parameter environment to be used for
183 /// obligations
b7449926 184 /// - `value` -- the value within which we are instantiating opaque types
dc9dc135 185 /// - `value_span` -- the span where the value came from, used in error reporting
ba9703b0 186 fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
ff7c6d11 187 &self,
f035d41b 188 parent_def_id: LocalDefId,
9fa01778 189 body_id: hir::HirId,
ff7c6d11 190 param_env: ty::ParamEnv<'tcx>,
fc512014 191 value: T,
dc9dc135 192 value_span: Span,
b7449926 193 ) -> InferOk<'tcx, (T, OpaqueTypeMap<'tcx>)> {
dc9dc135
XL
194 debug!(
195 "instantiate_opaque_types(value={:?}, parent_def_id={:?}, body_id={:?}, \
e1599b0c
XL
196 param_env={:?}, value_span={:?})",
197 value, parent_def_id, body_id, param_env, value_span,
ff7c6d11
XL
198 );
199 let mut instantiator = Instantiator {
200 infcx: self,
201 parent_def_id,
202 body_id,
203 param_env,
dc9dc135 204 value_span,
a1dfa0c6 205 opaque_types: Default::default(),
ff7c6d11
XL
206 obligations: vec![],
207 };
b7449926 208 let value = instantiator.instantiate_opaque_types_in_map(value);
dc9dc135 209 InferOk { value: (value, instantiator.opaque_types), obligations: instantiator.obligations }
ff7c6d11
XL
210 }
211
416331ca
XL
212 /// Given the map `opaque_types` containing the opaque
213 /// `impl Trait` types whose underlying, hidden types are being
ff7c6d11
XL
214 /// inferred, this method adds constraints to the regions
215 /// appearing in those underlying hidden types to ensure that they
216 /// at least do not refer to random scopes within the current
217 /// function. These constraints are not (quite) sufficient to
218 /// guarantee that the regions are actually legal values; that
219 /// final condition is imposed after region inference is done.
220 ///
221 /// # The Problem
222 ///
9fa01778 223 /// Let's work through an example to explain how it works. Assume
ff7c6d11
XL
224 /// the current function is as follows:
225 ///
226 /// ```text
227 /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
228 /// ```
229 ///
230 /// Here, we have two `impl Trait` types whose values are being
231 /// inferred (the `impl Bar<'a>` and the `impl
232 /// Bar<'b>`). Conceptually, this is sugar for a setup where we
416331ca 233 /// define underlying opaque types (`Foo1`, `Foo2`) and then, in
ff7c6d11
XL
234 /// the return type of `foo`, we *reference* those definitions:
235 ///
236 /// ```text
416331ca
XL
237 /// type Foo1<'x> = impl Bar<'x>;
238 /// type Foo2<'x> = impl Bar<'x>;
ff7c6d11
XL
239 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
240 /// // ^^^^ ^^
241 /// // | |
242 /// // | substs
243 /// // def_id
244 /// ```
245 ///
246 /// As indicating in the comments above, each of those references
247 /// is (in the compiler) basically a substitution (`substs`)
248 /// applied to the type of a suitable `def_id` (which identifies
249 /// `Foo1` or `Foo2`).
250 ///
251 /// Now, at this point in compilation, what we have done is to
252 /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
253 /// fresh inference variables C1 and C2. We wish to use the values
254 /// of these variables to infer the underlying types of `Foo1` and
9fa01778 255 /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
ff7c6d11
XL
256 /// constraints like:
257 ///
258 /// ```text
259 /// for<'a> (Foo1<'a> = C1)
260 /// for<'b> (Foo1<'b> = C2)
261 /// ```
262 ///
263 /// For these equation to be satisfiable, the types `C1` and `C2`
264 /// can only refer to a limited set of regions. For example, `C1`
265 /// can only refer to `'static` and `'a`, and `C2` can only refer
266 /// to `'static` and `'b`. The job of this function is to impose that
267 /// constraint.
268 ///
269 /// Up to this point, C1 and C2 are basically just random type
270 /// inference variables, and hence they may contain arbitrary
271 /// regions. In fact, it is fairly likely that they do! Consider
272 /// this possible definition of `foo`:
273 ///
274 /// ```text
275 /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
276 /// (&*x, &*y)
277 /// }
278 /// ```
279 ///
280 /// Here, the values for the concrete types of the two impl
281 /// traits will include inference variables:
282 ///
283 /// ```text
284 /// &'0 i32
285 /// &'1 i32
286 /// ```
287 ///
288 /// Ordinarily, the subtyping rules would ensure that these are
289 /// sufficiently large. But since `impl Bar<'a>` isn't a specific
9fa01778 290 /// type per se, we don't get such constraints by default. This
ff7c6d11
XL
291 /// is where this function comes into play. It adds extra
292 /// constraints to ensure that all the regions which appear in the
293 /// inferred type are regions that could validly appear.
294 ///
295 /// This is actually a bit of a tricky constraint in general. We
296 /// want to say that each variable (e.g., `'0`) can only take on
416331ca 297 /// values that were supplied as arguments to the opaque type
ff7c6d11
XL
298 /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
299 /// scope. We don't have a constraint quite of this kind in the current
300 /// region checker.
301 ///
302 /// # The Solution
303 ///
dc9dc135
XL
304 /// We generally prefer to make `<=` constraints, since they
305 /// integrate best into the region solver. To do that, we find the
306 /// "minimum" of all the arguments that appear in the substs: that
307 /// is, some region which is less than all the others. In the case
308 /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after
309 /// all). Then we apply that as a least bound to the variables
310 /// (e.g., `'a <= '0`).
ff7c6d11
XL
311 ///
312 /// In some cases, there is no minimum. Consider this example:
313 ///
314 /// ```text
315 /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
316 /// ```
317 ///
dc9dc135 318 /// Here we would report a more complex "in constraint", like `'r
74b04a01 319 /// in ['a, 'b, 'static]` (where `'r` is some region appearing in
dc9dc135
XL
320 /// the hidden type).
321 ///
322 /// # Constrain regions, not the hidden concrete type
323 ///
324 /// Note that generating constraints on each region `Rc` is *not*
325 /// the same as generating an outlives constraint on `Tc` iself.
326 /// For example, if we had a function like this:
327 ///
328 /// ```rust
329 /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
330 /// (x, y)
331 /// }
332 ///
333 /// // Equivalent to:
416331ca 334 /// type FooReturn<'a, T> = impl Foo<'a>;
dc9dc135
XL
335 /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. }
336 /// ```
337 ///
338 /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0`
339 /// is an inference variable). If we generated a constraint that
340 /// `Tc: 'a`, then this would incorrectly require that `T: 'a` --
416331ca 341 /// but this is not necessary, because the opaque type we
dc9dc135
XL
342 /// create will be allowed to reference `T`. So we only generate a
343 /// constraint that `'0: 'a`.
ff7c6d11
XL
344 ///
345 /// # The `free_region_relations` parameter
346 ///
347 /// The `free_region_relations` argument is used to find the
416331ca 348 /// "minimum" of the regions supplied to a given opaque type.
ff7c6d11
XL
349 /// It must be a relation that can answer whether `'a <= 'b`,
350 /// where `'a` and `'b` are regions that appear in the "substs"
416331ca 351 /// for the opaque type references (the `<'a>` in `Foo1<'a>`).
ff7c6d11
XL
352 ///
353 /// Note that we do not impose the constraints based on the
354 /// generic regions from the `Foo1` definition (e.g., `'x`). This
355 /// is because the constraints we are imposing here is basically
356 /// the concern of the one generating the constraining type C1,
357 /// which is the current function. It also means that we can
358 /// take "implied bounds" into account in some cases:
359 ///
360 /// ```text
361 /// trait SomeTrait<'a, 'b> { }
362 /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
363 /// ```
364 ///
365 /// Here, the fact that `'b: 'a` is known only because of the
366 /// implied bounds from the `&'a &'b u32` parameter, and is not
416331ca 367 /// "inherent" to the opaque type definition.
ff7c6d11
XL
368 ///
369 /// # Parameters
370 ///
b7449926 371 /// - `opaque_types` -- the map produced by `instantiate_opaque_types`
ff7c6d11
XL
372 /// - `free_region_relations` -- something that can be used to relate
373 /// the free regions (`'a`) that appear in the impl trait.
ba9703b0 374 fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(
ff7c6d11 375 &self,
b7449926 376 opaque_types: &OpaqueTypeMap<'tcx>,
ff7c6d11
XL
377 free_region_relations: &FRR,
378 ) {
b7449926 379 debug!("constrain_opaque_types()");
ff7c6d11 380
b7449926 381 for (&def_id, opaque_defn) in opaque_types {
74b04a01
XL
382 self.constrain_opaque_type(
383 def_id,
384 opaque_defn,
385 GenerateMemberConstraints::WhenRequired,
386 free_region_relations,
387 );
ff7c6d11
XL
388 }
389 }
390
dc9dc135 391 /// See `constrain_opaque_types` for documentation.
ba9703b0 392 fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
ff7c6d11
XL
393 &self,
394 def_id: DefId,
b7449926 395 opaque_defn: &OpaqueTypeDecl<'tcx>,
74b04a01 396 mode: GenerateMemberConstraints,
ff7c6d11
XL
397 free_region_relations: &FRR,
398 ) {
b7449926
XL
399 debug!("constrain_opaque_type()");
400 debug!("constrain_opaque_type: def_id={:?}", def_id);
401 debug!("constrain_opaque_type: opaque_defn={:#?}", opaque_defn);
ff7c6d11 402
48663c56
XL
403 let tcx = self.tcx;
404
fc512014 405 let concrete_ty = self.resolve_vars_if_possible(opaque_defn.concrete_ty);
ff7c6d11 406
b7449926 407 debug!("constrain_opaque_type: concrete_ty={:?}", concrete_ty);
ff7c6d11 408
f035d41b
XL
409 let first_own_region = match opaque_defn.origin {
410 hir::OpaqueTyOrigin::FnReturn | hir::OpaqueTyOrigin::AsyncFn => {
411 // We lower
412 //
413 // fn foo<'l0..'ln>() -> impl Trait<'l0..'lm>
414 //
415 // into
416 //
417 // type foo::<'p0..'pn>::Foo<'q0..'qm>
418 // fn foo<l0..'ln>() -> foo::<'static..'static>::Foo<'l0..'lm>.
419 //
420 // For these types we onlt iterate over `'l0..lm` below.
421 tcx.generics_of(def_id).parent_count
422 }
423 // These opaque type inherit all lifetime parameters from their
424 // parent, so we have to check them all.
6a06907d
XL
425 hir::OpaqueTyOrigin::Binding
426 | hir::OpaqueTyOrigin::TyAlias
427 | hir::OpaqueTyOrigin::Misc => 0,
f035d41b 428 };
ff7c6d11 429
48663c56 430 let span = tcx.def_span(def_id);
ff7c6d11 431
48663c56 432 // If there are required region bounds, we can use them.
b7449926 433 if opaque_defn.has_required_region_bounds {
29967ef6
XL
434 let bounds = tcx.explicit_item_bounds(def_id);
435 debug!("constrain_opaque_type: predicates: {:#?}", bounds);
436 let bounds: Vec<_> =
437 bounds.iter().map(|(bound, _)| bound.subst(tcx, opaque_defn.substs)).collect();
48663c56
XL
438 debug!("constrain_opaque_type: bounds={:#?}", bounds);
439 let opaque_type = tcx.mk_opaque(def_id, opaque_defn.substs);
440
dfeec247 441 let required_region_bounds =
29967ef6 442 required_region_bounds(tcx, opaque_type, bounds.into_iter());
48663c56
XL
443 debug_assert!(!required_region_bounds.is_empty());
444
dc9dc135
XL
445 for required_region in required_region_bounds {
446 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
dc9dc135 447 op: |r| self.sub_regions(infer::CallReturn(span), required_region, r),
48663c56
XL
448 });
449 }
74b04a01 450 if let GenerateMemberConstraints::IfNoStaticBound = mode {
f035d41b 451 self.generate_member_constraint(concrete_ty, opaque_defn, def_id, first_own_region);
74b04a01 452 }
ff7c6d11
XL
453 return;
454 }
455
456 // There were no `required_region_bounds`,
457 // so we have to search for a `least_region`.
458 // Go through all the regions used as arguments to the
416331ca 459 // opaque type. These are the parameters to the opaque
ff7c6d11
XL
460 // type; so in our example above, `substs` would contain
461 // `['a]` for the first impl trait and `'b` for the
462 // second.
463 let mut least_region = None;
dc9dc135 464
f035d41b
XL
465 for subst_arg in &opaque_defn.substs[first_own_region..] {
466 let subst_region = match subst_arg.unpack() {
467 GenericArgKind::Lifetime(r) => r,
468 GenericArgKind::Type(_) | GenericArgKind::Const(_) => continue,
469 };
ff7c6d11
XL
470
471 // Compute the least upper bound of it with the other regions.
b7449926 472 debug!("constrain_opaque_types: least_region={:?}", least_region);
f035d41b 473 debug!("constrain_opaque_types: subst_region={:?}", subst_region);
ff7c6d11 474 match least_region {
f035d41b 475 None => least_region = Some(subst_region),
ff7c6d11 476 Some(lr) => {
f035d41b 477 if free_region_relations.sub_free_regions(self.tcx, lr, subst_region) {
ff7c6d11 478 // keep the current least region
f035d41b
XL
479 } else if free_region_relations.sub_free_regions(self.tcx, subst_region, lr) {
480 // switch to `subst_region`
481 least_region = Some(subst_region);
ff7c6d11
XL
482 } else {
483 // There are two regions (`lr` and
f035d41b 484 // `subst_region`) which are not relatable. We
dc9dc135
XL
485 // can't find a best choice. Therefore,
486 // instead of creating a single bound like
487 // `'r: 'a` (which is our preferred choice),
488 // we will create a "in bound" like `'r in
489 // ['a, 'b, 'c]`, where `'a..'c` are the
490 // regions that appear in the impl trait.
74b04a01
XL
491
492 // For now, enforce a feature gate outside of async functions.
f035d41b 493 self.member_constraint_feature_gate(opaque_defn, def_id, lr, subst_region);
74b04a01 494
dc9dc135
XL
495 return self.generate_member_constraint(
496 concrete_ty,
dc9dc135
XL
497 opaque_defn,
498 def_id,
f035d41b 499 first_own_region,
dc9dc135 500 );
ff7c6d11
XL
501 }
502 }
503 }
504 }
505
48663c56 506 let least_region = least_region.unwrap_or(tcx.lifetimes.re_static);
b7449926 507 debug!("constrain_opaque_types: least_region={:?}", least_region);
ff7c6d11 508
74b04a01
XL
509 if let GenerateMemberConstraints::IfNoStaticBound = mode {
510 if least_region != tcx.lifetimes.re_static {
f035d41b 511 self.generate_member_constraint(concrete_ty, opaque_defn, def_id, first_own_region);
74b04a01
XL
512 }
513 }
dc9dc135 514 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
dc9dc135 515 op: |r| self.sub_regions(infer::CallReturn(span), least_region, r),
48663c56 516 });
ff7c6d11
XL
517 }
518
dc9dc135
XL
519 /// As a fallback, we sometimes generate an "in constraint". For
520 /// a case like `impl Foo<'a, 'b>`, where `'a` and `'b` cannot be
521 /// related, we would generate a constraint `'r in ['a, 'b,
522 /// 'static]` for each region `'r` that appears in the hidden type
523 /// (i.e., it must be equal to `'a`, `'b`, or `'static`).
524 ///
525 /// `conflict1` and `conflict2` are the two region bounds that we
526 /// detected which were unrelated. They are used for diagnostics.
527 fn generate_member_constraint(
528 &self,
529 concrete_ty: Ty<'tcx>,
dc9dc135
XL
530 opaque_defn: &OpaqueTypeDecl<'tcx>,
531 opaque_type_def_id: DefId,
f035d41b 532 first_own_region: usize,
dc9dc135 533 ) {
dc9dc135
XL
534 // Create the set of choice regions: each region in the hidden
535 // type can be equal to any of the region parameters of the
536 // opaque type definition.
537 let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new(
f035d41b 538 opaque_defn.substs[first_own_region..]
dc9dc135 539 .iter()
f035d41b
XL
540 .filter_map(|arg| match arg.unpack() {
541 GenericArgKind::Lifetime(r) => Some(r),
542 GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
dc9dc135 543 })
dc9dc135
XL
544 .chain(std::iter::once(self.tcx.lifetimes.re_static))
545 .collect(),
546 );
547
548 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
dfeec247
XL
549 op: |r| {
550 self.member_constraint(
551 opaque_type_def_id,
552 opaque_defn.definition_span,
553 concrete_ty,
554 r,
555 &choice_regions,
556 )
557 },
dc9dc135
XL
558 });
559 }
560
561 /// Member constraints are presently feature-gated except for
562 /// async-await. We expect to lift this once we've had a bit more
563 /// time.
564 fn member_constraint_feature_gate(
565 &self,
566 opaque_defn: &OpaqueTypeDecl<'tcx>,
567 opaque_type_def_id: DefId,
568 conflict1: ty::Region<'tcx>,
569 conflict2: ty::Region<'tcx>,
570 ) -> bool {
571 // If we have `#![feature(member_constraints)]`, no problems.
572 if self.tcx.features().member_constraints {
573 return false;
574 }
575
576 let span = self.tcx.def_span(opaque_type_def_id);
577
578 // Without a feature-gate, we only generate member-constraints for async-await.
579 let context_name = match opaque_defn.origin {
580 // No feature-gate required for `async fn`.
416331ca 581 hir::OpaqueTyOrigin::AsyncFn => return false,
dc9dc135
XL
582
583 // Otherwise, generate the label we'll use in the error message.
f035d41b 584 hir::OpaqueTyOrigin::Binding
74b04a01 585 | hir::OpaqueTyOrigin::FnReturn
6a06907d 586 | hir::OpaqueTyOrigin::TyAlias
74b04a01 587 | hir::OpaqueTyOrigin::Misc => "impl Trait",
dc9dc135
XL
588 };
589 let msg = format!("ambiguous lifetime bound in `{}`", context_name);
590 let mut err = self.tcx.sess.struct_span_err(span, &msg);
591
592 let conflict1_name = conflict1.to_string();
593 let conflict2_name = conflict2.to_string();
594 let label_owned;
595 let label = match (&*conflict1_name, &*conflict2_name) {
596 ("'_", "'_") => "the elided lifetimes here do not outlive one another",
597 _ => {
598 label_owned = format!(
599 "neither `{}` nor `{}` outlives the other",
600 conflict1_name, conflict2_name,
601 );
602 &label_owned
603 }
604 };
605 err.span_label(span, label);
606
fc512014 607 if self.tcx.sess.is_nightly_build() {
dfeec247 608 err.help("add #![feature(member_constraints)] to the crate attributes to enable");
dc9dc135
XL
609 }
610
611 err.emit();
612 true
613 }
614
b7449926 615 /// Given the fully resolved, instantiated type for an opaque
ff7c6d11 616 /// type, i.e., the value of an inference variable like C1 or C2
416331ca 617 /// (*), computes the "definition type" for an opaque type
ff7c6d11
XL
618 /// definition -- that is, the inferred value of `Foo1<'x>` or
619 /// `Foo2<'x>` that we would conceptually use in its definition:
620 ///
416331ca
XL
621 /// type Foo1<'x> = impl Bar<'x> = AAA; <-- this type AAA
622 /// type Foo2<'x> = impl Bar<'x> = BBB; <-- or this type BBB
ff7c6d11
XL
623 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
624 ///
625 /// Note that these values are defined in terms of a distinct set of
626 /// generic parameters (`'x` instead of `'a`) from C1 or C2. The main
627 /// purpose of this function is to do that translation.
628 ///
629 /// (*) C1 and C2 were introduced in the comments on
b7449926 630 /// `constrain_opaque_types`. Read that comment for more context.
ff7c6d11
XL
631 ///
632 /// # Parameters
633 ///
634 /// - `def_id`, the `impl Trait` type
74b04a01 635 /// - `substs`, the substs used to instantiate this opaque type
ff7c6d11 636 /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of
b7449926 637 /// `opaque_defn.concrete_ty`
ba9703b0 638 fn infer_opaque_definition_from_instantiation(
ff7c6d11
XL
639 &self,
640 def_id: DefId,
74b04a01 641 substs: SubstsRef<'tcx>,
dc9dc135 642 instantiated_ty: Ty<'tcx>,
416331ca 643 span: Span,
dc9dc135 644 ) -> Ty<'tcx> {
ff7c6d11 645 debug!(
b7449926 646 "infer_opaque_definition_from_instantiation(def_id={:?}, instantiated_ty={:?})",
8faf50e0 647 def_id, instantiated_ty
ff7c6d11
XL
648 );
649
ff7c6d11
XL
650 // Use substs to build up a reverse map from regions to their
651 // identity mappings. This is necessary because of `impl
652 // Trait` lifetimes are computed by replacing existing
653 // lifetimes with 'static and remapping only those used in the
654 // `impl Trait` return type, resulting in the parameters
655 // shifting.
e74abb32 656 let id_substs = InternalSubsts::identity_for_item(self.tcx, def_id);
74b04a01 657 let map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>> =
f9f354fc 658 substs.iter().enumerate().map(|(index, subst)| (subst, id_substs[index])).collect();
ff7c6d11
XL
659
660 // Convert the type from the function into a type valid outside
661 // the function, by replacing invalid regions with 'static,
662 // after producing an error for each of them.
dc9dc135
XL
663 let definition_ty = instantiated_ty.fold_with(&mut ReverseMapper::new(
664 self.tcx,
665 self.is_tainted_by_errors(),
666 def_id,
667 map,
668 instantiated_ty,
416331ca 669 span,
dc9dc135
XL
670 ));
671 debug!("infer_opaque_definition_from_instantiation: definition_ty={:?}", definition_ty);
0531ce1d 672
ff7c6d11
XL
673 definition_ty
674 }
675}
676
48663c56
XL
677// Visitor that requires that (almost) all regions in the type visited outlive
678// `least_region`. We cannot use `push_outlives_components` because regions in
679// closure signatures are not included in their outlives components. We need to
680// ensure all regions outlive the given bound so that we don't end up with,
f9f354fc 681// say, `ReVar` appearing in a return type and causing ICEs when other
48663c56
XL
682// functions end up with region constraints involving regions from other
683// functions.
684//
685// We also cannot use `for_each_free_region` because for closures it includes
686// the regions parameters from the enclosing item.
687//
688// We ignore any type parameters because impl trait values are assumed to
689// capture all the in-scope type parameters.
ba9703b0 690struct ConstrainOpaqueTypeRegionVisitor<OP> {
dc9dc135 691 op: OP,
48663c56
XL
692}
693
ba9703b0 694impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<OP>
dc9dc135
XL
695where
696 OP: FnMut(ty::Region<'tcx>),
48663c56 697{
fc512014
XL
698 fn visit_binder<T: TypeFoldable<'tcx>>(
699 &mut self,
cdc7bbd5 700 t: &ty::Binder<'tcx, T>,
fc512014 701 ) -> ControlFlow<Self::BreakTy> {
f035d41b 702 t.as_ref().skip_binder().visit_with(self);
29967ef6 703 ControlFlow::CONTINUE
48663c56
XL
704 }
705
fc512014 706 fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
48663c56
XL
707 match *r {
708 // ignore bound regions, keep visiting
29967ef6 709 ty::ReLateBound(_, _) => ControlFlow::CONTINUE,
48663c56 710 _ => {
dc9dc135 711 (self.op)(r);
29967ef6 712 ControlFlow::CONTINUE
48663c56
XL
713 }
714 }
715 }
716
fc512014 717 fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
48663c56 718 // We're only interested in types involving regions
1b1a35ee 719 if !ty.flags().intersects(ty::TypeFlags::HAS_FREE_REGIONS) {
29967ef6 720 return ControlFlow::CONTINUE;
48663c56
XL
721 }
722
1b1a35ee 723 match ty.kind() {
ba9703b0 724 ty::Closure(_, ref substs) => {
48663c56
XL
725 // Skip lifetime parameters of the enclosing item(s)
726
29967ef6 727 substs.as_closure().tupled_upvars_ty().visit_with(self);
ba9703b0 728 substs.as_closure().sig_as_fn_ptr_ty().visit_with(self);
48663c56
XL
729 }
730
ba9703b0 731 ty::Generator(_, ref substs, _) => {
48663c56
XL
732 // Skip lifetime parameters of the enclosing item(s)
733 // Also skip the witness type, because that has no free regions.
734
29967ef6 735 substs.as_generator().tupled_upvars_ty().visit_with(self);
ba9703b0
XL
736 substs.as_generator().return_ty().visit_with(self);
737 substs.as_generator().yield_ty().visit_with(self);
738 substs.as_generator().resume_ty().visit_with(self);
48663c56
XL
739 }
740 _ => {
741 ty.super_visit_with(self);
742 }
743 }
744
29967ef6 745 ControlFlow::CONTINUE
48663c56
XL
746 }
747}
748
dc9dc135
XL
749struct ReverseMapper<'tcx> {
750 tcx: TyCtxt<'tcx>,
0531ce1d
XL
751
752 /// If errors have already been reported in this fn, we suppress
753 /// our own errors because they are sometimes derivative.
754 tainted_by_errors: bool,
755
b7449926 756 opaque_type_def_id: DefId,
e74abb32 757 map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>,
0531ce1d
XL
758 map_missing_regions_to_empty: bool,
759
760 /// initially `Some`, set to `None` once error has been reported
761 hidden_ty: Option<Ty<'tcx>>,
416331ca
XL
762
763 /// Span of function being checked.
764 span: Span,
0531ce1d
XL
765}
766
dc9dc135 767impl ReverseMapper<'tcx> {
0531ce1d 768 fn new(
dc9dc135 769 tcx: TyCtxt<'tcx>,
0531ce1d 770 tainted_by_errors: bool,
b7449926 771 opaque_type_def_id: DefId,
e74abb32 772 map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>,
0531ce1d 773 hidden_ty: Ty<'tcx>,
416331ca 774 span: Span,
0531ce1d
XL
775 ) -> Self {
776 Self {
777 tcx,
778 tainted_by_errors,
b7449926 779 opaque_type_def_id,
0531ce1d
XL
780 map,
781 map_missing_regions_to_empty: false,
782 hidden_ty: Some(hidden_ty),
416331ca 783 span,
0531ce1d
XL
784 }
785 }
786
e74abb32
XL
787 fn fold_kind_mapping_missing_regions_to_empty(
788 &mut self,
789 kind: GenericArg<'tcx>,
790 ) -> GenericArg<'tcx> {
0531ce1d
XL
791 assert!(!self.map_missing_regions_to_empty);
792 self.map_missing_regions_to_empty = true;
793 let kind = kind.fold_with(self);
794 self.map_missing_regions_to_empty = false;
795 kind
796 }
797
e74abb32 798 fn fold_kind_normally(&mut self, kind: GenericArg<'tcx>) -> GenericArg<'tcx> {
0531ce1d
XL
799 assert!(!self.map_missing_regions_to_empty);
800 kind.fold_with(self)
801 }
802}
803
dc9dc135
XL
804impl TypeFolder<'tcx> for ReverseMapper<'tcx> {
805 fn tcx(&self) -> TyCtxt<'tcx> {
0531ce1d
XL
806 self.tcx
807 }
808
809 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
810 match r {
74b04a01
XL
811 // Ignore bound regions and `'static` regions that appear in the
812 // type, we only need to remap regions that reference lifetimes
813 // from the function declaraion.
814 // This would ignore `'r` in a type like `for<'r> fn(&'r u32)`.
815 ty::ReLateBound(..) | ty::ReStatic => return r,
816
817 // If regions have been erased (by writeback), don't try to unerase
818 // them.
819 ty::ReErased => return r,
820
821 // The regions that we expect from borrow checking.
822 ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReEmpty(ty::UniverseIndex::ROOT) => {}
823
f9f354fc 824 ty::ReEmpty(_) | ty::RePlaceholder(_) | ty::ReVar(_) => {
74b04a01
XL
825 // All of the regions in the type should either have been
826 // erased by writeback, or mapped back to named regions by
827 // borrow checking.
828 bug!("unexpected region kind in opaque type: {:?}", r);
829 }
0531ce1d
XL
830 }
831
416331ca 832 let generics = self.tcx().generics_of(self.opaque_type_def_id);
0531ce1d 833 match self.map.get(&r.into()).map(|k| k.unpack()) {
e74abb32 834 Some(GenericArgKind::Lifetime(r1)) => r1,
0531ce1d 835 Some(u) => panic!("region mapped to unexpected kind: {:?}", u),
74b04a01
XL
836 None if self.map_missing_regions_to_empty || self.tainted_by_errors => {
837 self.tcx.lifetimes.re_root_empty
838 }
416331ca 839 None if generics.parent.is_some() => {
74b04a01
XL
840 if let Some(hidden_ty) = self.hidden_ty.take() {
841 unexpected_hidden_region_diagnostic(
842 self.tcx,
74b04a01
XL
843 self.tcx.def_span(self.opaque_type_def_id),
844 hidden_ty,
845 r,
846 )
847 .emit();
0531ce1d 848 }
74b04a01 849 self.tcx.lifetimes.re_root_empty
dc9dc135 850 }
416331ca 851 None => {
dfeec247
XL
852 self.tcx
853 .sess
854 .struct_span_err(self.span, "non-defining opaque type use in defining scope")
416331ca
XL
855 .span_label(
856 self.span,
dfeec247
XL
857 format!(
858 "lifetime `{}` is part of concrete type but not used in \
859 parameter list of the `impl Trait` type alias",
860 r
861 ),
416331ca
XL
862 )
863 .emit();
864
74b04a01 865 self.tcx().lifetimes.re_static
dfeec247 866 }
0531ce1d
XL
867 }
868 }
869
870 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
1b1a35ee 871 match *ty.kind() {
b7449926 872 ty::Closure(def_id, substs) => {
0531ce1d
XL
873 // I am a horrible monster and I pray for death. When
874 // we encounter a closure here, it is always a closure
875 // from within the function that we are currently
876 // type-checking -- one that is now being encapsulated
416331ca 877 // in an opaque type. Ideally, we would
0531ce1d
XL
878 // go through the types/lifetimes that it references
879 // and treat them just like we would any other type,
880 // which means we would error out if we find any
881 // reference to a type/region that is not in the
882 // "reverse map".
883 //
884 // **However,** in the case of closures, there is a
885 // somewhat subtle (read: hacky) consideration. The
886 // problem is that our closure types currently include
887 // all the lifetime parameters declared on the
888 // enclosing function, even if they are unused by the
889 // closure itself. We can't readily filter them out,
890 // so here we replace those values with `'empty`. This
891 // can't really make a difference to the rest of the
892 // compiler; those regions are ignored for the
893 // outlives relation, and hence don't affect trait
894 // selection or auto traits, and they are erased
94b46f34 895 // during codegen.
0531ce1d
XL
896
897 let generics = self.tcx.generics_of(def_id);
f9f354fc 898 let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, kind)| {
dfeec247
XL
899 if index < generics.parent_count {
900 // Accommodate missing regions in the parent kinds...
901 self.fold_kind_mapping_missing_regions_to_empty(kind)
902 } else {
903 // ...but not elsewhere.
904 self.fold_kind_normally(kind)
905 }
906 }));
0531ce1d 907
e74abb32 908 self.tcx.mk_closure(def_id, substs)
0531ce1d
XL
909 }
910
48663c56
XL
911 ty::Generator(def_id, substs, movability) => {
912 let generics = self.tcx.generics_of(def_id);
f9f354fc 913 let substs = self.tcx.mk_substs(substs.iter().enumerate().map(|(index, kind)| {
dfeec247
XL
914 if index < generics.parent_count {
915 // Accommodate missing regions in the parent kinds...
916 self.fold_kind_mapping_missing_regions_to_empty(kind)
917 } else {
918 // ...but not elsewhere.
919 self.fold_kind_normally(kind)
920 }
921 }));
48663c56 922
e74abb32 923 self.tcx.mk_generator(def_id, substs, movability)
48663c56
XL
924 }
925
416331ca
XL
926 ty::Param(..) => {
927 // Look it up in the substitution list.
928 match self.map.get(&ty.into()).map(|k| k.unpack()) {
929 // Found it in the substitution list; replace with the parameter from the
930 // opaque type.
e74abb32 931 Some(GenericArgKind::Type(t1)) => t1,
416331ca
XL
932 Some(u) => panic!("type mapped to unexpected kind: {:?}", u),
933 None => {
dfeec247
XL
934 self.tcx
935 .sess
416331ca
XL
936 .struct_span_err(
937 self.span,
dfeec247
XL
938 &format!(
939 "type parameter `{}` is part of concrete type but not \
416331ca 940 used in parameter list for the `impl Trait` type alias",
dfeec247
XL
941 ty
942 ),
416331ca
XL
943 )
944 .emit();
945
f035d41b 946 self.tcx().ty_error()
416331ca
XL
947 }
948 }
949 }
950
0531ce1d
XL
951 _ => ty.super_fold_with(self),
952 }
953 }
416331ca
XL
954
955 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
956 trace!("checking const {:?}", ct);
957 // Find a const parameter
958 match ct.val {
60c5eb7d 959 ty::ConstKind::Param(..) => {
416331ca
XL
960 // Look it up in the substitution list.
961 match self.map.get(&ct.into()).map(|k| k.unpack()) {
962 // Found it in the substitution list, replace with the parameter from the
963 // opaque type.
e74abb32 964 Some(GenericArgKind::Const(c1)) => c1,
416331ca
XL
965 Some(u) => panic!("const mapped to unexpected kind: {:?}", u),
966 None => {
dfeec247
XL
967 self.tcx
968 .sess
416331ca
XL
969 .struct_span_err(
970 self.span,
dfeec247
XL
971 &format!(
972 "const parameter `{}` is part of concrete type but not \
416331ca 973 used in parameter list for the `impl Trait` type alias",
dfeec247
XL
974 ct
975 ),
416331ca
XL
976 )
977 .emit();
978
f035d41b 979 self.tcx().const_error(ct.ty)
416331ca
XL
980 }
981 }
982 }
983
984 _ => ct,
985 }
986 }
0531ce1d
XL
987}
988
dc9dc135
XL
989struct Instantiator<'a, 'tcx> {
990 infcx: &'a InferCtxt<'a, 'tcx>,
f035d41b 991 parent_def_id: LocalDefId,
9fa01778 992 body_id: hir::HirId,
ff7c6d11 993 param_env: ty::ParamEnv<'tcx>,
dc9dc135 994 value_span: Span,
b7449926 995 opaque_types: OpaqueTypeMap<'tcx>,
ff7c6d11
XL
996 obligations: Vec<PredicateObligation<'tcx>>,
997}
998
dc9dc135 999impl<'a, 'tcx> Instantiator<'a, 'tcx> {
fc512014 1000 fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
b7449926 1001 debug!("instantiate_opaque_types_in_map(value={:?})", value);
ff7c6d11
XL
1002 let tcx = self.infcx.tcx;
1003 value.fold_with(&mut BottomUpFolder {
1004 tcx,
48663c56 1005 ty_op: |ty| {
e74abb32 1006 if ty.references_error() {
f035d41b 1007 return tcx.ty_error();
1b1a35ee 1008 } else if let ty::Opaque(def_id, substs) = ty.kind() {
ff7c6d11
XL
1009 // Check that this is `impl Trait` type is
1010 // declared by `parent_def_id` -- i.e., one whose
1011 // value we are inferring. At present, this is
1012 // always true during the first phase of
1013 // type-check, but not always true later on during
416331ca 1014 // NLL. Once we support named opaque types more fully,
ff7c6d11
XL
1015 // this same scenario will be able to arise during all phases.
1016 //
416331ca
XL
1017 // Here is an example using type alias `impl Trait`
1018 // that indicates the distinction we are checking for:
ff7c6d11
XL
1019 //
1020 // ```rust
1021 // mod a {
416331ca 1022 // pub type Foo = impl Iterator;
ff7c6d11
XL
1023 // pub fn make_foo() -> Foo { .. }
1024 // }
1025 //
1026 // mod b {
1027 // fn foo() -> a::Foo { a::make_foo() }
1028 // }
1029 // ```
1030 //
1031 // Here, the return type of `foo` references a
b7449926 1032 // `Opaque` indeed, but not one whose value is
ff7c6d11
XL
1033 // presently being inferred. You can get into a
1034 // similar situation with closure return types
1035 // today:
1036 //
1037 // ```rust
1038 // fn foo() -> impl Iterator { .. }
1039 // fn bar() {
b7449926 1040 // let x = || foo(); // returns the Opaque assoc with `foo`
ff7c6d11
XL
1041 // }
1042 // ```
f9f354fc 1043 if let Some(def_id) = def_id.as_local() {
3dfed10e 1044 let opaque_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
8faf50e0
XL
1045 let parent_def_id = self.parent_def_id;
1046 let def_scope_default = || {
532ac7d7 1047 let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id);
f035d41b 1048 parent_def_id == tcx.hir().local_def_id(opaque_parent_hir_id)
8faf50e0 1049 };
dc9dc135 1050 let (in_definition_scope, origin) = match tcx.hir().find(opaque_hir_id) {
e74abb32 1051 Some(Node::Item(item)) => match item.kind {
dc9dc135 1052 // Anonymous `impl Trait`
416331ca 1053 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
8faf50e0 1054 impl_trait_fn: Some(parent),
532ac7d7 1055 origin,
8faf50e0 1056 ..
f035d41b 1057 }) => (parent == self.parent_def_id.to_def_id(), origin),
416331ca
XL
1058 // Named `type Foo = impl Bar;`
1059 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
8faf50e0 1060 impl_trait_fn: None,
532ac7d7 1061 origin,
8faf50e0 1062 ..
532ac7d7 1063 }) => (
f035d41b 1064 may_define_opaque_type(tcx, self.parent_def_id, opaque_hir_id),
532ac7d7 1065 origin,
8faf50e0 1066 ),
f035d41b 1067 _ => (def_scope_default(), hir::OpaqueTyOrigin::Misc),
94b46f34 1068 },
8faf50e0 1069 _ => bug!(
f035d41b 1070 "expected item, found {}",
dc9dc135 1071 tcx.hir().node_to_string(opaque_hir_id),
8faf50e0 1072 ),
94b46f34 1073 };
8faf50e0 1074 if in_definition_scope {
f9f354fc 1075 return self.fold_opaque_ty(ty, def_id.to_def_id(), substs, origin);
ff7c6d11
XL
1076 }
1077
0531ce1d 1078 debug!(
b7449926 1079 "instantiate_opaque_types_in_map: \
0bf4aa26 1080 encountered opaque outside its definition scope \
8faf50e0
XL
1081 def_id={:?}",
1082 def_id,
0531ce1d 1083 );
ff7c6d11
XL
1084 }
1085 }
1086
1087 ty
1088 },
48663c56
XL
1089 lt_op: |lt| lt,
1090 ct_op: |ct| ct,
ff7c6d11
XL
1091 })
1092 }
1093
b7449926 1094 fn fold_opaque_ty(
ff7c6d11
XL
1095 &mut self,
1096 ty: Ty<'tcx>,
1097 def_id: DefId,
532ac7d7 1098 substs: SubstsRef<'tcx>,
416331ca 1099 origin: hir::OpaqueTyOrigin,
ff7c6d11
XL
1100 ) -> Ty<'tcx> {
1101 let infcx = self.infcx;
1102 let tcx = infcx.tcx;
1103
dc9dc135 1104 debug!("instantiate_opaque_types: Opaque(def_id={:?}, substs={:?})", def_id, substs);
ff7c6d11 1105
dc9dc135 1106 // Use the same type variable if the exact same opaque type appears more
0731742a 1107 // than once in the return type (e.g., if it's passed to a type alias).
b7449926 1108 if let Some(opaque_defn) = self.opaque_types.get(&def_id) {
e1599b0c 1109 debug!("instantiate_opaque_types: returning concrete ty {:?}", opaque_defn.concrete_ty);
b7449926 1110 return opaque_defn.concrete_ty;
ff7c6d11
XL
1111 }
1112 let span = tcx.def_span(def_id);
e1599b0c 1113 debug!("fold_opaque_ty {:?} {:?}", self.value_span, span);
dc9dc135
XL
1114 let ty_var = infcx
1115 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
ff7c6d11 1116
29967ef6
XL
1117 let item_bounds = tcx.explicit_item_bounds(def_id);
1118 debug!("instantiate_opaque_types: bounds={:#?}", item_bounds);
1119 let bounds: Vec<_> =
1120 item_bounds.iter().map(|(bound, _)| bound.subst(tcx, substs)).collect();
416331ca
XL
1121
1122 let param_env = tcx.param_env(def_id);
1123 let InferOk { value: bounds, obligations } =
fc512014 1124 infcx.partially_normalize_associated_types_in(span, self.body_id, param_env, bounds);
416331ca
XL
1125 self.obligations.extend(obligations);
1126
b7449926 1127 debug!("instantiate_opaque_types: bounds={:?}", bounds);
ff7c6d11 1128
29967ef6 1129 let required_region_bounds = required_region_bounds(tcx, ty, bounds.iter().copied());
dc9dc135 1130 debug!("instantiate_opaque_types: required_region_bounds={:?}", required_region_bounds);
ff7c6d11 1131
dc9dc135 1132 // Make sure that we are in fact defining the *entire* type
416331ca 1133 // (e.g., `type Foo<T: Bound> = impl Bar;` needs to be
dc9dc135
XL
1134 // defined by a function like `fn foo<T: Bound>() -> Foo<T>`).
1135 debug!("instantiate_opaque_types: param_env={:#?}", self.param_env,);
1136 debug!("instantiate_opaque_types: generics={:#?}", tcx.generics_of(def_id),);
1137
1138 // Ideally, we'd get the span where *this specific `ty` came
1139 // from*, but right now we just use the span from the overall
1140 // value being folded. In simple cases like `-> impl Foo`,
1141 // these are the same span, but not in cases like `-> (impl
1142 // Foo, impl Bar)`.
1143 let definition_span = self.value_span;
8faf50e0 1144
b7449926 1145 self.opaque_types.insert(
ff7c6d11 1146 def_id,
b7449926 1147 OpaqueTypeDecl {
60c5eb7d 1148 opaque_type: ty,
ff7c6d11 1149 substs,
dc9dc135 1150 definition_span,
ff7c6d11
XL
1151 concrete_ty: ty_var,
1152 has_required_region_bounds: !required_region_bounds.is_empty(),
532ac7d7 1153 origin,
ff7c6d11
XL
1154 },
1155 );
b7449926 1156 debug!("instantiate_opaque_types: ty_var={:?}", ty_var);
ff7c6d11 1157
29967ef6 1158 for predicate in &bounds {
5869c6ff 1159 if let ty::PredicateKind::Projection(projection) = predicate.kind().skip_binder() {
3dfed10e 1160 if projection.ty.references_error() {
e74abb32
XL
1161 // No point on adding these obligations since there's a type error involved.
1162 return ty_var;
1163 }
1164 }
1165 }
1166
29967ef6
XL
1167 self.obligations.reserve(bounds.len());
1168 for predicate in bounds {
ff7c6d11 1169 // Change the predicate to refer to the type variable,
0bf4aa26
XL
1170 // which will be the concrete type instead of the opaque type.
1171 // This also instantiates nested instances of `impl Trait`.
fc512014 1172 let predicate = self.instantiate_opaque_types_in_map(predicate);
ff7c6d11 1173
cdc7bbd5 1174 let cause = traits::ObligationCause::new(span, self.body_id, traits::OpaqueType);
ff7c6d11
XL
1175
1176 // Require that the predicate holds for the concrete type.
b7449926 1177 debug!("instantiate_opaque_types: predicate={:?}", predicate);
dc9dc135 1178 self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate));
ff7c6d11
XL
1179 }
1180
1181 ty_var
1182 }
1183}
8faf50e0 1184
dc9dc135 1185/// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
8faf50e0 1186///
dc9dc135 1187/// Example:
8faf50e0
XL
1188/// ```rust
1189/// pub mod foo {
1190/// pub mod bar {
416331ca
XL
1191/// pub trait Bar { .. }
1192///
1193/// pub type Baz = impl Bar;
8faf50e0
XL
1194///
1195/// fn f1() -> Baz { .. }
1196/// }
1197///
1198/// fn f2() -> bar::Baz { .. }
1199/// }
1200/// ```
1201///
f9f354fc 1202/// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
416331ca 1203/// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
dc9dc135 1204/// For the above example, this function returns `true` for `f1` and `false` for `f2`.
f9f354fc
XL
1205pub fn may_define_opaque_type(
1206 tcx: TyCtxt<'_>,
1207 def_id: LocalDefId,
1208 opaque_hir_id: hir::HirId,
1209) -> bool {
3dfed10e 1210 let mut hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
dc9dc135 1211
416331ca 1212 // Named opaque types can be defined by any siblings or children of siblings.
e74abb32 1213 let scope = tcx.hir().get_defining_scope(opaque_hir_id);
dc9dc135
XL
1214 // We walk up the node tree until we hit the root or the scope of the opaque type.
1215 while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
532ac7d7 1216 hir_id = tcx.hir().get_parent_item(hir_id);
8faf50e0 1217 }
dc9dc135 1218 // Syntactically, we are allowed to define the concrete type if:
416331ca
XL
1219 let res = hir_id == scope;
1220 trace!(
1221 "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}",
dfeec247 1222 tcx.hir().find(hir_id),
416331ca
XL
1223 tcx.hir().get(opaque_hir_id),
1224 res
1225 );
1226 res
8faf50e0 1227}
dfeec247
XL
1228
1229/// Given a set of predicates that apply to an object type, returns
1230/// the region bounds that the (erased) `Self` type must
1231/// outlive. Precisely *because* the `Self` type is erased, the
1232/// parameter `erased_self_ty` must be supplied to indicate what type
1233/// has been used to represent `Self` in the predicates
1234/// themselves. This should really be a unique type; `FreshTy(0)` is a
1235/// popular choice.
1236///
1237/// N.B., in some cases, particularly around higher-ranked bounds,
1238/// this function returns a kind of conservative approximation.
1239/// That is, all regions returned by this function are definitely
1240/// required, but there may be other region bounds that are not
1241/// returned, as well as requirements like `for<'a> T: 'a`.
1242///
1243/// Requires that trait definitions have been processed so that we can
1244/// elaborate predicates and walk supertraits.
dfeec247
XL
1245crate fn required_region_bounds(
1246 tcx: TyCtxt<'tcx>,
1247 erased_self_ty: Ty<'tcx>,
ba9703b0 1248 predicates: impl Iterator<Item = ty::Predicate<'tcx>>,
dfeec247 1249) -> Vec<ty::Region<'tcx>> {
ba9703b0 1250 debug!("required_region_bounds(erased_self_ty={:?})", erased_self_ty);
dfeec247
XL
1251
1252 assert!(!erased_self_ty.has_escaping_bound_vars());
1253
1254 traits::elaborate_predicates(tcx, predicates)
ba9703b0
XL
1255 .filter_map(|obligation| {
1256 debug!("required_region_bounds(obligation={:?})", obligation);
5869c6ff
XL
1257 match obligation.predicate.kind().skip_binder() {
1258 ty::PredicateKind::Projection(..)
1259 | ty::PredicateKind::Trait(..)
1260 | ty::PredicateKind::Subtype(..)
1261 | ty::PredicateKind::WellFormed(..)
1262 | ty::PredicateKind::ObjectSafe(..)
1263 | ty::PredicateKind::ClosureKind(..)
1264 | ty::PredicateKind::RegionOutlives(..)
1265 | ty::PredicateKind::ConstEvaluatable(..)
1266 | ty::PredicateKind::ConstEquate(..)
1267 | ty::PredicateKind::TypeWellFormedFromEnv(..) => None,
1268 ty::PredicateKind::TypeOutlives(ty::OutlivesPredicate(ref t, ref r)) => {
dfeec247
XL
1269 // Search for a bound of the form `erased_self_ty
1270 // : 'a`, but be wary of something like `for<'a>
1271 // erased_self_ty : 'a` (we interpret a
1272 // higher-ranked bound like that as 'static,
1273 // though at present the code in `fulfill.rs`
1274 // considers such bounds to be unsatisfiable, so
1275 // it's kind of a moot point since you could never
1276 // construct such an object, but this seems
1277 // correct even if that code changes).
dfeec247
XL
1278 if t == &erased_self_ty && !r.has_escaping_bound_vars() {
1279 Some(*r)
1280 } else {
1281 None
1282 }
1283 }
1284 }
1285 })
1286 .collect()
1287}