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