]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/opaque_types.rs
0b1c59d092f2be4695ac3bc10e1b8f4a46c4d242
[rust.git] / compiler / rustc_infer / src / infer / opaque_types.rs
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;
5 use rustc_data_structures::vec_map::VecMap;
6 use rustc_hir as hir;
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};
11 use rustc_span::Span;
12
13 use std::ops::ControlFlow;
14
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 }
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 {
279             hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..) => {
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     fn opaque_type_origin(&self, def_id: LocalDefId) -> Option<hir::OpaqueTyOrigin> {
333         let tcx = self.tcx;
334         let opaque_hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
335         let parent_def_id = self.defining_use_anchor?;
336         let item_kind = &tcx.hir().expect_item(def_id).kind;
337         let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, ..  }) = item_kind else {
338             span_bug!(
339                 tcx.def_span(def_id),
340                 "weird opaque type: {:#?}",
341                 item_kind
342             )
343         };
344         let in_definition_scope = match *origin {
345             // Async `impl Trait`
346             hir::OpaqueTyOrigin::AsyncFn(parent) => parent == parent_def_id,
347             // Anonymous `impl Trait`
348             hir::OpaqueTyOrigin::FnReturn(parent) => parent == parent_def_id,
349             // Named `type Foo = impl Bar;`
350             hir::OpaqueTyOrigin::TyAlias => {
351                 may_define_opaque_type(tcx, parent_def_id, opaque_hir_id)
352             }
353         };
354         in_definition_scope.then_some(*origin)
355     }
356 }
357
358 // Visitor that requires that (almost) all regions in the type visited outlive
359 // `least_region`. We cannot use `push_outlives_components` because regions in
360 // closure signatures are not included in their outlives components. We need to
361 // ensure all regions outlive the given bound so that we don't end up with,
362 // say, `ReVar` appearing in a return type and causing ICEs when other
363 // functions end up with region constraints involving regions from other
364 // functions.
365 //
366 // We also cannot use `for_each_free_region` because for closures it includes
367 // the regions parameters from the enclosing item.
368 //
369 // We ignore any type parameters because impl trait values are assumed to
370 // capture all the in-scope type parameters.
371 struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP> {
372     tcx: TyCtxt<'tcx>,
373     op: OP,
374 }
375
376 impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
377 where
378     OP: FnMut(ty::Region<'tcx>),
379 {
380     fn tcx_for_anon_const_substs(&self) -> Option<TyCtxt<'tcx>> {
381         Some(self.tcx)
382     }
383
384     fn visit_binder<T: TypeFoldable<'tcx>>(
385         &mut self,
386         t: &ty::Binder<'tcx, T>,
387     ) -> ControlFlow<Self::BreakTy> {
388         t.as_ref().skip_binder().visit_with(self);
389         ControlFlow::CONTINUE
390     }
391
392     fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
393         match *r {
394             // ignore bound regions, keep visiting
395             ty::ReLateBound(_, _) => ControlFlow::CONTINUE,
396             _ => {
397                 (self.op)(r);
398                 ControlFlow::CONTINUE
399             }
400         }
401     }
402
403     fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
404         // We're only interested in types involving regions
405         if !ty.flags().intersects(ty::TypeFlags::HAS_POTENTIAL_FREE_REGIONS) {
406             return ControlFlow::CONTINUE;
407         }
408
409         match ty.kind() {
410             ty::Closure(_, ref substs) => {
411                 // Skip lifetime parameters of the enclosing item(s)
412
413                 substs.as_closure().tupled_upvars_ty().visit_with(self);
414                 substs.as_closure().sig_as_fn_ptr_ty().visit_with(self);
415             }
416
417             ty::Generator(_, ref substs, _) => {
418                 // Skip lifetime parameters of the enclosing item(s)
419                 // Also skip the witness type, because that has no free regions.
420
421                 substs.as_generator().tupled_upvars_ty().visit_with(self);
422                 substs.as_generator().return_ty().visit_with(self);
423                 substs.as_generator().yield_ty().visit_with(self);
424                 substs.as_generator().resume_ty().visit_with(self);
425             }
426             _ => {
427                 ty.super_visit_with(self);
428             }
429         }
430
431         ControlFlow::CONTINUE
432     }
433 }
434
435 struct Instantiator<'a, 'tcx> {
436     infcx: &'a InferCtxt<'a, 'tcx>,
437     body_id: hir::HirId,
438     param_env: ty::ParamEnv<'tcx>,
439     value_span: Span,
440     obligations: Vec<traits::PredicateObligation<'tcx>>,
441 }
442
443 impl<'a, 'tcx> Instantiator<'a, 'tcx> {
444     fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: T) -> T {
445         let tcx = self.infcx.tcx;
446         value.fold_with(&mut BottomUpFolder {
447             tcx,
448             ty_op: |ty| {
449                 if ty.references_error() {
450                     return tcx.ty_error();
451                 } else if let ty::Opaque(def_id, substs) = ty.kind() {
452                     // Check that this is `impl Trait` type is
453                     // declared by `parent_def_id` -- i.e., one whose
454                     // value we are inferring.  At present, this is
455                     // always true during the first phase of
456                     // type-check, but not always true later on during
457                     // NLL. Once we support named opaque types more fully,
458                     // this same scenario will be able to arise during all phases.
459                     //
460                     // Here is an example using type alias `impl Trait`
461                     // that indicates the distinction we are checking for:
462                     //
463                     // ```rust
464                     // mod a {
465                     //   pub type Foo = impl Iterator;
466                     //   pub fn make_foo() -> Foo { .. }
467                     // }
468                     //
469                     // mod b {
470                     //   fn foo() -> a::Foo { a::make_foo() }
471                     // }
472                     // ```
473                     //
474                     // Here, the return type of `foo` references an
475                     // `Opaque` indeed, but not one whose value is
476                     // presently being inferred. You can get into a
477                     // similar situation with closure return types
478                     // today:
479                     //
480                     // ```rust
481                     // fn foo() -> impl Iterator { .. }
482                     // fn bar() {
483                     //     let x = || foo(); // returns the Opaque assoc with `foo`
484                     // }
485                     // ```
486                     if let Some(def_id) = def_id.as_local() {
487                         if let Some(origin) = self.infcx.opaque_type_origin(def_id) {
488                             let opaque_type_key =
489                                 OpaqueTypeKey { def_id: def_id.to_def_id(), substs };
490                             return self.fold_opaque_ty(ty, opaque_type_key, origin);
491                         }
492
493                         debug!(
494                             "instantiate_opaque_types_in_map: \
495                              encountered opaque outside its definition scope \
496                              def_id={:?}",
497                             def_id,
498                         );
499                     }
500                 }
501
502                 ty
503             },
504             lt_op: |lt| lt,
505             ct_op: |ct| ct,
506         })
507     }
508
509     #[instrument(skip(self), level = "debug")]
510     fn fold_opaque_ty(
511         &mut self,
512         ty: Ty<'tcx>,
513         opaque_type_key: OpaqueTypeKey<'tcx>,
514         origin: hir::OpaqueTyOrigin,
515     ) -> Ty<'tcx> {
516         let infcx = self.infcx;
517         let tcx = infcx.tcx;
518         let OpaqueTypeKey { def_id, substs } = opaque_type_key;
519
520         // Use the same type variable if the exact same opaque type appears more
521         // than once in the return type (e.g., if it's passed to a type alias).
522         if let Some(opaque_defn) = infcx.inner.borrow().opaque_types.get(&opaque_type_key) {
523             debug!("re-using cached concrete type {:?}", opaque_defn.concrete_ty.kind());
524             return opaque_defn.concrete_ty;
525         }
526
527         let ty_var = infcx.next_ty_var(TypeVariableOrigin {
528             kind: TypeVariableOriginKind::TypeInference,
529             span: self.value_span,
530         });
531
532         // Ideally, we'd get the span where *this specific `ty` came
533         // from*, but right now we just use the span from the overall
534         // value being folded. In simple cases like `-> impl Foo`,
535         // these are the same span, but not in cases like `-> (impl
536         // Foo, impl Bar)`.
537         let definition_span = self.value_span;
538
539         {
540             let mut infcx = self.infcx.inner.borrow_mut();
541             infcx.opaque_types.insert(
542                 OpaqueTypeKey { def_id, substs },
543                 OpaqueTypeDecl { opaque_type: ty, definition_span, concrete_ty: ty_var, origin },
544             );
545             infcx.opaque_types_vars.insert(ty_var, ty);
546         }
547
548         debug!("generated new type inference var {:?}", ty_var.kind());
549
550         let item_bounds = tcx.explicit_item_bounds(def_id);
551
552         self.obligations.reserve(item_bounds.len());
553         for (predicate, _) in item_bounds {
554             debug!(?predicate);
555             let predicate = predicate.subst(tcx, substs);
556             debug!(?predicate);
557
558             let predicate = predicate.fold_with(&mut BottomUpFolder {
559                 tcx,
560                 ty_op: |ty| match *ty.kind() {
561                     // Replace all other mentions of the same opaque type with the hidden type,
562                     // as the bounds must hold on the hidden type after all.
563                     ty::Opaque(def_id2, substs2) if def_id == def_id2 && substs == substs2 => {
564                         ty_var
565                     }
566                     // Instantiate nested instances of `impl Trait`.
567                     ty::Opaque(..) => self.instantiate_opaque_types_in_map(ty),
568                     _ => ty,
569                 },
570                 lt_op: |lt| lt,
571                 ct_op: |ct| ct,
572             });
573
574             // We can't normalize associated types from `rustc_infer`, but we can eagerly register inference variables for them.
575             let predicate = predicate.fold_with(&mut BottomUpFolder {
576                 tcx,
577                 ty_op: |ty| match ty.kind() {
578                     ty::Projection(projection_ty) => infcx.infer_projection(
579                         self.param_env,
580                         *projection_ty,
581                         traits::ObligationCause::misc(self.value_span, self.body_id),
582                         0,
583                         &mut self.obligations,
584                     ),
585                     _ => ty,
586                 },
587                 lt_op: |lt| lt,
588                 ct_op: |ct| ct,
589             });
590             debug!(?predicate);
591
592             if let ty::PredicateKind::Projection(projection) = predicate.kind().skip_binder() {
593                 if projection.ty.references_error() {
594                     // No point on adding these obligations since there's a type error involved.
595                     return tcx.ty_error();
596                 }
597             }
598
599             let cause =
600                 traits::ObligationCause::new(self.value_span, self.body_id, traits::OpaqueType);
601
602             // Require that the predicate holds for the concrete type.
603             debug!(?predicate);
604             self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate));
605         }
606
607         ty_var
608     }
609 }
610
611 /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
612 ///
613 /// Example:
614 /// ```rust
615 /// pub mod foo {
616 ///     pub mod bar {
617 ///         pub trait Bar { .. }
618 ///
619 ///         pub type Baz = impl Bar;
620 ///
621 ///         fn f1() -> Baz { .. }
622 ///     }
623 ///
624 ///     fn f2() -> bar::Baz { .. }
625 /// }
626 /// ```
627 ///
628 /// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
629 /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
630 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
631 fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hir::HirId) -> bool {
632     let mut hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
633
634     // Named opaque types can be defined by any siblings or children of siblings.
635     let scope = tcx.hir().get_defining_scope(opaque_hir_id);
636     // We walk up the node tree until we hit the root or the scope of the opaque type.
637     while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
638         hir_id = tcx.hir().local_def_id_to_hir_id(tcx.hir().get_parent_item(hir_id));
639     }
640     // Syntactically, we are allowed to define the concrete type if:
641     let res = hir_id == scope;
642     trace!(
643         "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}",
644         tcx.hir().find(hir_id),
645         tcx.hir().get(opaque_hir_id),
646         res
647     );
648     res
649 }