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