]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_infer/src/infer/opaque_types.rs
Auto merge of #105094 - Swatinem:generator-not-future, r=compiler-errors
[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>, a_is_expected| 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                     a_is_expected,
173                 ))
174             }
175             _ => None,
176         };
177         if let Some(res) = process(a, b, true) {
178             res
179         } else if let Some(res) = process(b, a, false) {
180             res
181         } else {
182             let (a, b) = self.resolve_vars_if_possible((a, b));
183             Err(TypeError::Sorts(ExpectedFound::new(true, a, b)))
184         }
185     }
186
187     /// Given the map `opaque_types` containing the opaque
188     /// `impl Trait` types whose underlying, hidden types are being
189     /// inferred, this method adds constraints to the regions
190     /// appearing in those underlying hidden types to ensure that they
191     /// at least do not refer to random scopes within the current
192     /// function. These constraints are not (quite) sufficient to
193     /// guarantee that the regions are actually legal values; that
194     /// final condition is imposed after region inference is done.
195     ///
196     /// # The Problem
197     ///
198     /// Let's work through an example to explain how it works. Assume
199     /// the current function is as follows:
200     ///
201     /// ```text
202     /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
203     /// ```
204     ///
205     /// Here, we have two `impl Trait` types whose values are being
206     /// inferred (the `impl Bar<'a>` and the `impl
207     /// Bar<'b>`). Conceptually, this is sugar for a setup where we
208     /// define underlying opaque types (`Foo1`, `Foo2`) and then, in
209     /// the return type of `foo`, we *reference* those definitions:
210     ///
211     /// ```text
212     /// type Foo1<'x> = impl Bar<'x>;
213     /// type Foo2<'x> = impl Bar<'x>;
214     /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
215     ///                    //  ^^^^ ^^
216     ///                    //  |    |
217     ///                    //  |    substs
218     ///                    //  def_id
219     /// ```
220     ///
221     /// As indicating in the comments above, each of those references
222     /// is (in the compiler) basically a substitution (`substs`)
223     /// applied to the type of a suitable `def_id` (which identifies
224     /// `Foo1` or `Foo2`).
225     ///
226     /// Now, at this point in compilation, what we have done is to
227     /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
228     /// fresh inference variables C1 and C2. We wish to use the values
229     /// of these variables to infer the underlying types of `Foo1` and
230     /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
231     /// constraints like:
232     ///
233     /// ```text
234     /// for<'a> (Foo1<'a> = C1)
235     /// for<'b> (Foo1<'b> = C2)
236     /// ```
237     ///
238     /// For these equation to be satisfiable, the types `C1` and `C2`
239     /// can only refer to a limited set of regions. For example, `C1`
240     /// can only refer to `'static` and `'a`, and `C2` can only refer
241     /// to `'static` and `'b`. The job of this function is to impose that
242     /// constraint.
243     ///
244     /// Up to this point, C1 and C2 are basically just random type
245     /// inference variables, and hence they may contain arbitrary
246     /// regions. In fact, it is fairly likely that they do! Consider
247     /// this possible definition of `foo`:
248     ///
249     /// ```text
250     /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
251     ///         (&*x, &*y)
252     ///     }
253     /// ```
254     ///
255     /// Here, the values for the concrete types of the two impl
256     /// traits will include inference variables:
257     ///
258     /// ```text
259     /// &'0 i32
260     /// &'1 i32
261     /// ```
262     ///
263     /// Ordinarily, the subtyping rules would ensure that these are
264     /// sufficiently large. But since `impl Bar<'a>` isn't a specific
265     /// type per se, we don't get such constraints by default. This
266     /// is where this function comes into play. It adds extra
267     /// constraints to ensure that all the regions which appear in the
268     /// inferred type are regions that could validly appear.
269     ///
270     /// This is actually a bit of a tricky constraint in general. We
271     /// want to say that each variable (e.g., `'0`) can only take on
272     /// values that were supplied as arguments to the opaque type
273     /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
274     /// scope. We don't have a constraint quite of this kind in the current
275     /// region checker.
276     ///
277     /// # The Solution
278     ///
279     /// We generally prefer to make `<=` constraints, since they
280     /// integrate best into the region solver. To do that, we find the
281     /// "minimum" of all the arguments that appear in the substs: that
282     /// is, some region which is less than all the others. In the case
283     /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after
284     /// all). Then we apply that as a least bound to the variables
285     /// (e.g., `'a <= '0`).
286     ///
287     /// In some cases, there is no minimum. Consider this example:
288     ///
289     /// ```text
290     /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
291     /// ```
292     ///
293     /// Here we would report a more complex "in constraint", like `'r
294     /// in ['a, 'b, 'static]` (where `'r` is some region appearing in
295     /// the hidden type).
296     ///
297     /// # Constrain regions, not the hidden concrete type
298     ///
299     /// Note that generating constraints on each region `Rc` is *not*
300     /// the same as generating an outlives constraint on `Tc` itself.
301     /// For example, if we had a function like this:
302     ///
303     /// ```
304     /// # #![feature(type_alias_impl_trait)]
305     /// # fn main() {}
306     /// # trait Foo<'a> {}
307     /// # impl<'a, T> Foo<'a> for (&'a u32, T) {}
308     /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
309     ///   (x, y)
310     /// }
311     ///
312     /// // Equivalent to:
313     /// # mod dummy { use super::*;
314     /// type FooReturn<'a, T> = impl Foo<'a>;
315     /// fn foo<'a, T>(x: &'a u32, y: T) -> FooReturn<'a, T> {
316     ///   (x, y)
317     /// }
318     /// # }
319     /// ```
320     ///
321     /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0`
322     /// is an inference variable). If we generated a constraint that
323     /// `Tc: 'a`, then this would incorrectly require that `T: 'a` --
324     /// but this is not necessary, because the opaque type we
325     /// create will be allowed to reference `T`. So we only generate a
326     /// constraint that `'0: 'a`.
327     #[instrument(level = "debug", skip(self))]
328     pub fn register_member_constraints(
329         &self,
330         param_env: ty::ParamEnv<'tcx>,
331         opaque_type_key: OpaqueTypeKey<'tcx>,
332         concrete_ty: Ty<'tcx>,
333         span: Span,
334     ) {
335         let concrete_ty = self.resolve_vars_if_possible(concrete_ty);
336         debug!(?concrete_ty);
337
338         let variances = self.tcx.variances_of(opaque_type_key.def_id);
339         debug!(?variances);
340
341         // For a case like `impl Foo<'a, 'b>`, we would generate a constraint
342         // `'r in ['a, 'b, 'static]` for each region `'r` that appears in the
343         // hidden type (i.e., it must be equal to `'a`, `'b`, or `'static`).
344         //
345         // `conflict1` and `conflict2` are the two region bounds that we
346         // detected which were unrelated. They are used for diagnostics.
347
348         // Create the set of choice regions: each region in the hidden
349         // type can be equal to any of the region parameters of the
350         // opaque type definition.
351         let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new(
352             opaque_type_key
353                 .substs
354                 .iter()
355                 .enumerate()
356                 .filter(|(i, _)| variances[*i] == ty::Variance::Invariant)
357                 .filter_map(|(_, arg)| match arg.unpack() {
358                     GenericArgKind::Lifetime(r) => Some(r),
359                     GenericArgKind::Type(_) | GenericArgKind::Const(_) => None,
360                 })
361                 .chain(std::iter::once(self.tcx.lifetimes.re_static))
362                 .collect(),
363         );
364
365         concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
366             tcx: self.tcx,
367             op: |r| self.member_constraint(opaque_type_key, span, concrete_ty, r, &choice_regions),
368         });
369     }
370
371     #[instrument(skip(self), level = "trace", ret)]
372     pub fn opaque_type_origin(&self, def_id: LocalDefId, span: Span) -> Option<OpaqueTyOrigin> {
373         let opaque_hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id);
374         let parent_def_id = match self.defining_use_anchor {
375             DefiningAnchor::Bubble | DefiningAnchor::Error => return None,
376             DefiningAnchor::Bind(bind) => bind,
377         };
378         let item_kind = &self.tcx.hir().expect_item(def_id).kind;
379
380         let hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, ..  }) = item_kind else {
381             span_bug!(
382                 span,
383                 "weird opaque type: {:#?}, {:#?}",
384                 def_id,
385                 item_kind
386             )
387         };
388         let in_definition_scope = match *origin {
389             // Async `impl Trait`
390             hir::OpaqueTyOrigin::AsyncFn(parent) => parent == parent_def_id,
391             // Anonymous `impl Trait`
392             hir::OpaqueTyOrigin::FnReturn(parent) => parent == parent_def_id,
393             // Named `type Foo = impl Bar;`
394             hir::OpaqueTyOrigin::TyAlias => {
395                 may_define_opaque_type(self.tcx, parent_def_id, opaque_hir_id)
396             }
397         };
398         trace!(?origin);
399         in_definition_scope.then_some(*origin)
400     }
401
402     #[instrument(skip(self), level = "trace", ret)]
403     fn opaque_ty_origin_unchecked(&self, def_id: LocalDefId, span: Span) -> OpaqueTyOrigin {
404         match self.tcx.hir().expect_item(def_id).kind {
405             hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => origin,
406             ref itemkind => {
407                 span_bug!(span, "weird opaque type: {:?}, {:#?}", def_id, itemkind)
408             }
409         }
410     }
411 }
412
413 /// Visitor that requires that (almost) all regions in the type visited outlive
414 /// `least_region`. We cannot use `push_outlives_components` because regions in
415 /// closure signatures are not included in their outlives components. We need to
416 /// ensure all regions outlive the given bound so that we don't end up with,
417 /// say, `ReVar` appearing in a return type and causing ICEs when other
418 /// functions end up with region constraints involving regions from other
419 /// functions.
420 ///
421 /// We also cannot use `for_each_free_region` because for closures it includes
422 /// the regions parameters from the enclosing item.
423 ///
424 /// We ignore any type parameters because impl trait values are assumed to
425 /// capture all the in-scope type parameters.
426 pub struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP: FnMut(ty::Region<'tcx>)> {
427     pub tcx: TyCtxt<'tcx>,
428     pub op: OP,
429 }
430
431 impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
432 where
433     OP: FnMut(ty::Region<'tcx>),
434 {
435     fn visit_binder<T: TypeVisitable<'tcx>>(
436         &mut self,
437         t: &ty::Binder<'tcx, T>,
438     ) -> ControlFlow<Self::BreakTy> {
439         t.super_visit_with(self);
440         ControlFlow::CONTINUE
441     }
442
443     fn visit_region(&mut self, r: ty::Region<'tcx>) -> ControlFlow<Self::BreakTy> {
444         match *r {
445             // ignore bound regions, keep visiting
446             ty::ReLateBound(_, _) => ControlFlow::CONTINUE,
447             _ => {
448                 (self.op)(r);
449                 ControlFlow::CONTINUE
450             }
451         }
452     }
453
454     fn visit_ty(&mut self, ty: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
455         // We're only interested in types involving regions
456         if !ty.flags().intersects(ty::TypeFlags::HAS_FREE_REGIONS) {
457             return ControlFlow::CONTINUE;
458         }
459
460         match ty.kind() {
461             ty::Closure(_, ref substs) => {
462                 // Skip lifetime parameters of the enclosing item(s)
463
464                 substs.as_closure().tupled_upvars_ty().visit_with(self);
465                 substs.as_closure().sig_as_fn_ptr_ty().visit_with(self);
466             }
467
468             ty::Generator(_, ref substs, _) => {
469                 // Skip lifetime parameters of the enclosing item(s)
470                 // Also skip the witness type, because that has no free regions.
471
472                 substs.as_generator().tupled_upvars_ty().visit_with(self);
473                 substs.as_generator().return_ty().visit_with(self);
474                 substs.as_generator().yield_ty().visit_with(self);
475                 substs.as_generator().resume_ty().visit_with(self);
476             }
477
478             ty::Opaque(def_id, ref substs) => {
479                 // Skip lifetime paramters that are not captures.
480                 let variances = self.tcx.variances_of(*def_id);
481
482                 for (v, s) in std::iter::zip(variances, substs.iter()) {
483                     if *v != ty::Variance::Bivariant {
484                         s.visit_with(self);
485                     }
486                 }
487             }
488
489             ty::Projection(proj)
490                 if self.tcx.def_kind(proj.item_def_id) == DefKind::ImplTraitPlaceholder =>
491             {
492                 // Skip lifetime paramters that are not captures.
493                 let variances = self.tcx.variances_of(proj.item_def_id);
494
495                 for (v, s) in std::iter::zip(variances, proj.substs.iter()) {
496                     if *v != ty::Variance::Bivariant {
497                         s.visit_with(self);
498                     }
499                 }
500             }
501
502             _ => {
503                 ty.super_visit_with(self);
504             }
505         }
506
507         ControlFlow::CONTINUE
508     }
509 }
510
511 pub enum UseKind {
512     DefiningUse,
513     OpaqueUse,
514 }
515
516 impl UseKind {
517     pub fn is_defining(self) -> bool {
518         match self {
519             UseKind::DefiningUse => true,
520             UseKind::OpaqueUse => false,
521         }
522     }
523 }
524
525 impl<'tcx> InferCtxt<'tcx> {
526     #[instrument(skip(self), level = "debug")]
527     fn register_hidden_type(
528         &self,
529         opaque_type_key: OpaqueTypeKey<'tcx>,
530         cause: ObligationCause<'tcx>,
531         param_env: ty::ParamEnv<'tcx>,
532         hidden_ty: Ty<'tcx>,
533         origin: hir::OpaqueTyOrigin,
534         a_is_expected: bool,
535     ) -> InferResult<'tcx, ()> {
536         let tcx = self.tcx;
537         let OpaqueTypeKey { def_id, substs } = opaque_type_key;
538
539         // Ideally, we'd get the span where *this specific `ty` came
540         // from*, but right now we just use the span from the overall
541         // value being folded. In simple cases like `-> impl Foo`,
542         // these are the same span, but not in cases like `-> (impl
543         // Foo, impl Bar)`.
544         let span = cause.span;
545
546         let mut obligations = vec![];
547         let prev = self.inner.borrow_mut().opaque_types().register(
548             OpaqueTypeKey { def_id, substs },
549             OpaqueHiddenType { ty: hidden_ty, span },
550             origin,
551         );
552         if let Some(prev) = prev {
553             obligations =
554                 self.at(&cause, param_env).eq_exp(a_is_expected, prev, hidden_ty)?.obligations;
555         }
556
557         let item_bounds = tcx.bound_explicit_item_bounds(def_id.to_def_id());
558
559         for (predicate, _) in item_bounds.subst_iter_copied(tcx, substs) {
560             let predicate = predicate.fold_with(&mut BottomUpFolder {
561                 tcx,
562                 ty_op: |ty| match *ty.kind() {
563                     // We can't normalize associated types from `rustc_infer`,
564                     // but we can eagerly register inference variables for them.
565                     // FIXME(RPITIT): Don't replace RPITITs with inference vars.
566                     ty::Projection(projection_ty)
567                         if !projection_ty.has_escaping_bound_vars()
568                             && tcx.def_kind(projection_ty.item_def_id)
569                                 != DefKind::ImplTraitPlaceholder =>
570                     {
571                         self.infer_projection(
572                             param_env,
573                             projection_ty,
574                             cause.clone(),
575                             0,
576                             &mut obligations,
577                         )
578                     }
579                     // Replace all other mentions of the same opaque type with the hidden type,
580                     // as the bounds must hold on the hidden type after all.
581                     ty::Opaque(def_id2, substs2)
582                         if def_id.to_def_id() == def_id2 && substs == substs2 =>
583                     {
584                         hidden_ty
585                     }
586                     // FIXME(RPITIT): This can go away when we move to associated types
587                     ty::Projection(proj)
588                         if def_id.to_def_id() == proj.item_def_id && substs == proj.substs =>
589                     {
590                         hidden_ty
591                     }
592                     _ => ty,
593                 },
594                 lt_op: |lt| lt,
595                 ct_op: |ct| ct,
596             });
597
598             if let ty::PredicateKind::Clause(ty::Clause::Projection(projection)) =
599                 predicate.kind().skip_binder()
600             {
601                 if projection.term.references_error() {
602                     // No point on adding these obligations since there's a type error involved.
603                     return Ok(InferOk { value: (), obligations: vec![] });
604                 }
605                 trace!("{:#?}", projection.term);
606             }
607             // Require that the predicate holds for the concrete type.
608             debug!(?predicate);
609             obligations.push(traits::Obligation::new(
610                 self.tcx,
611                 cause.clone(),
612                 param_env,
613                 predicate,
614             ));
615         }
616         Ok(InferOk { value: (), obligations })
617     }
618 }
619
620 /// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
621 ///
622 /// Example:
623 /// ```ignore UNSOLVED (is this a bug?)
624 /// # #![feature(type_alias_impl_trait)]
625 /// pub mod foo {
626 ///     pub mod bar {
627 ///         pub trait Bar { /* ... */ }
628 ///         pub type Baz = impl Bar;
629 ///
630 ///         # impl Bar for () {}
631 ///         fn f1() -> Baz { /* ... */ }
632 ///     }
633 ///     fn f2() -> bar::Baz { /* ... */ }
634 /// }
635 /// ```
636 ///
637 /// Here, `def_id` is the `LocalDefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
638 /// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
639 /// For the above example, this function returns `true` for `f1` and `false` for `f2`.
640 fn may_define_opaque_type(tcx: TyCtxt<'_>, def_id: LocalDefId, opaque_hir_id: hir::HirId) -> bool {
641     let mut hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
642
643     // Named opaque types can be defined by any siblings or children of siblings.
644     let scope = tcx.hir().get_defining_scope(opaque_hir_id);
645     // We walk up the node tree until we hit the root or the scope of the opaque type.
646     while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
647         hir_id = tcx.hir().get_parent_item(hir_id).into();
648     }
649     // Syntactically, we are allowed to define the concrete type if:
650     let res = hir_id == scope;
651     trace!(
652         "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}",
653         tcx.hir().find(hir_id),
654         tcx.hir().get(opaque_hir_id),
655         res
656     );
657     res
658 }