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