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