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