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