]> git.proxmox.com Git - rustc.git/blame - src/librustc/infer/opaque_types/mod.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / src / librustc / infer / opaque_types / mod.rs
CommitLineData
9fa01778 1use crate::hir;
dc9dc135 2use crate::hir::def_id::DefId;
9fa01778 3use crate::hir::Node;
9fa01778 4use crate::infer::outlives::free_region_map::FreeRegionRelations;
dc9dc135
XL
5use crate::infer::{self, InferCtxt, InferOk, TypeVariableOrigin, TypeVariableOriginKind};
6use crate::middle::region;
9fa01778 7use crate::traits::{self, PredicateObligation};
48663c56 8use crate::ty::fold::{BottomUpFolder, TypeFoldable, TypeFolder, TypeVisitor};
e74abb32 9use crate::ty::subst::{InternalSubsts, GenericArg, SubstsRef, GenericArgKind};
dc9dc135 10use crate::ty::{self, GenericParamDefKind, Ty, TyCtxt};
9fa01778 11use crate::util::nodemap::DefIdMap;
dc9dc135
XL
12use errors::DiagnosticBuilder;
13use rustc::session::config::nightly_options;
14use rustc_data_structures::fx::FxHashMap;
15use rustc_data_structures::sync::Lrc;
16use syntax_pos::Span;
ff7c6d11 17
60c5eb7d
XL
18use rustc_error_codes::*;
19
b7449926 20pub type OpaqueTypeMap<'tcx> = DefIdMap<OpaqueTypeDecl<'tcx>>;
ff7c6d11 21
416331ca 22/// Information about the opaque types whose values we
ff7c6d11
XL
23/// are inferring in this function (these are the `impl Trait` that
24/// appear in the return type).
25#[derive(Copy, Clone, Debug)]
b7449926 26pub struct OpaqueTypeDecl<'tcx> {
60c5eb7d
XL
27
28 /// The opaque type (`ty::Opaque`) for this declaration.
29 pub opaque_type: Ty<'tcx>,
30
416331ca 31 /// The substitutions that we apply to the opaque type that this
ff7c6d11
XL
32 /// `impl Trait` desugars to. e.g., if:
33 ///
34 /// fn foo<'a, 'b, T>() -> impl Trait<'a>
35 ///
36 /// winds up desugared to:
37 ///
416331ca 38 /// type Foo<'x, X> = impl Trait<'x>
ff7c6d11
XL
39 /// fn foo<'a, 'b, T>() -> Foo<'a, T>
40 ///
41 /// then `substs` would be `['a, T]`.
532ac7d7 42 pub substs: SubstsRef<'tcx>,
ff7c6d11 43
dc9dc135
XL
44 /// The span of this particular definition of the opaque type. So
45 /// for example:
46 ///
47 /// ```
416331ca 48 /// type Foo = impl Baz;
dc9dc135
XL
49 /// fn bar() -> Foo {
50 /// ^^^ This is the span we are looking for!
51 /// ```
52 ///
53 /// In cases where the fn returns `(impl Trait, impl Trait)` or
54 /// other such combinations, the result is currently
55 /// over-approximated, but better than nothing.
56 pub definition_span: Span,
57
416331ca 58 /// The type variable that represents the value of the opaque type
ff7c6d11
XL
59 /// that we require. In other words, after we compile this function,
60 /// we will be created a constraint like:
61 ///
62 /// Foo<'a, T> = ?C
63 ///
64 /// where `?C` is the value of this type variable. =) It may
65 /// naturally refer to the type and lifetime parameters in scope
66 /// in this function, though ultimately it should only reference
67 /// those that are arguments to `Foo` in the constraint above. (In
68 /// other words, `?C` should not include `'b`, even though it's a
69 /// lifetime parameter on `foo`.)
70 pub concrete_ty: Ty<'tcx>,
71
9fa01778 72 /// Returns `true` if the `impl Trait` bounds include region bounds.
ff7c6d11
XL
73 /// For example, this would be true for:
74 ///
75 /// fn foo<'a, 'b, 'c>() -> impl Trait<'c> + 'a + 'b
76 ///
77 /// but false for:
78 ///
79 /// fn foo<'c>() -> impl Trait<'c>
80 ///
81 /// unless `Trait` was declared like:
82 ///
83 /// trait Trait<'c>: 'c
84 ///
85 /// in which case it would be true.
86 ///
87 /// This is used during regionck to decide whether we need to
88 /// impose any additional constraints to ensure that region
89 /// variables in `concrete_ty` wind up being constrained to
90 /// something from `substs` (or, at minimum, things that outlive
91 /// the fn body). (Ultimately, writeback is responsible for this
92 /// check.)
93 pub has_required_region_bounds: bool,
532ac7d7 94
416331ca
XL
95 /// The origin of the opaque type.
96 pub origin: hir::OpaqueTyOrigin,
ff7c6d11
XL
97}
98
dc9dc135 99impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
9fa01778 100 /// Replaces all opaque types in `value` with fresh inference variables
ff7c6d11
XL
101 /// and creates appropriate obligations. For example, given the input:
102 ///
103 /// impl Iterator<Item = impl Debug>
104 ///
105 /// this method would create two type variables, `?0` and `?1`. It would
106 /// return the type `?0` but also the obligations:
107 ///
108 /// ?0: Iterator<Item = ?1>
109 /// ?1: Debug
110 ///
b7449926 111 /// Moreover, it returns a `OpaqueTypeMap` that would map `?0` to
ff7c6d11
XL
112 /// info about the `impl Iterator<..>` type and `?1` to info about
113 /// the `impl Debug` type.
114 ///
115 /// # Parameters
116 ///
9fa01778 117 /// - `parent_def_id` -- the `DefId` of the function in which the opaque type
0bf4aa26 118 /// is defined
ff7c6d11
XL
119 /// - `body_id` -- the body-id with which the resulting obligations should
120 /// be associated
121 /// - `param_env` -- the in-scope parameter environment to be used for
122 /// obligations
b7449926 123 /// - `value` -- the value within which we are instantiating opaque types
dc9dc135 124 /// - `value_span` -- the span where the value came from, used in error reporting
b7449926 125 pub fn instantiate_opaque_types<T: TypeFoldable<'tcx>>(
ff7c6d11
XL
126 &self,
127 parent_def_id: DefId,
9fa01778 128 body_id: hir::HirId,
ff7c6d11
XL
129 param_env: ty::ParamEnv<'tcx>,
130 value: &T,
dc9dc135 131 value_span: Span,
b7449926 132 ) -> InferOk<'tcx, (T, OpaqueTypeMap<'tcx>)> {
dc9dc135
XL
133 debug!(
134 "instantiate_opaque_types(value={:?}, parent_def_id={:?}, body_id={:?}, \
e1599b0c
XL
135 param_env={:?}, value_span={:?})",
136 value, parent_def_id, body_id, param_env, value_span,
ff7c6d11
XL
137 );
138 let mut instantiator = Instantiator {
139 infcx: self,
140 parent_def_id,
141 body_id,
142 param_env,
dc9dc135 143 value_span,
a1dfa0c6 144 opaque_types: Default::default(),
ff7c6d11
XL
145 obligations: vec![],
146 };
b7449926 147 let value = instantiator.instantiate_opaque_types_in_map(value);
dc9dc135 148 InferOk { value: (value, instantiator.opaque_types), obligations: instantiator.obligations }
ff7c6d11
XL
149 }
150
416331ca
XL
151 /// Given the map `opaque_types` containing the opaque
152 /// `impl Trait` types whose underlying, hidden types are being
ff7c6d11
XL
153 /// inferred, this method adds constraints to the regions
154 /// appearing in those underlying hidden types to ensure that they
155 /// at least do not refer to random scopes within the current
156 /// function. These constraints are not (quite) sufficient to
157 /// guarantee that the regions are actually legal values; that
158 /// final condition is imposed after region inference is done.
159 ///
160 /// # The Problem
161 ///
9fa01778 162 /// Let's work through an example to explain how it works. Assume
ff7c6d11
XL
163 /// the current function is as follows:
164 ///
165 /// ```text
166 /// fn foo<'a, 'b>(..) -> (impl Bar<'a>, impl Bar<'b>)
167 /// ```
168 ///
169 /// Here, we have two `impl Trait` types whose values are being
170 /// inferred (the `impl Bar<'a>` and the `impl
171 /// Bar<'b>`). Conceptually, this is sugar for a setup where we
416331ca 172 /// define underlying opaque types (`Foo1`, `Foo2`) and then, in
ff7c6d11
XL
173 /// the return type of `foo`, we *reference* those definitions:
174 ///
175 /// ```text
416331ca
XL
176 /// type Foo1<'x> = impl Bar<'x>;
177 /// type Foo2<'x> = impl Bar<'x>;
ff7c6d11
XL
178 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
179 /// // ^^^^ ^^
180 /// // | |
181 /// // | substs
182 /// // def_id
183 /// ```
184 ///
185 /// As indicating in the comments above, each of those references
186 /// is (in the compiler) basically a substitution (`substs`)
187 /// applied to the type of a suitable `def_id` (which identifies
188 /// `Foo1` or `Foo2`).
189 ///
190 /// Now, at this point in compilation, what we have done is to
191 /// replace each of the references (`Foo1<'a>`, `Foo2<'b>`) with
192 /// fresh inference variables C1 and C2. We wish to use the values
193 /// of these variables to infer the underlying types of `Foo1` and
9fa01778 194 /// `Foo2`. That is, this gives rise to higher-order (pattern) unification
ff7c6d11
XL
195 /// constraints like:
196 ///
197 /// ```text
198 /// for<'a> (Foo1<'a> = C1)
199 /// for<'b> (Foo1<'b> = C2)
200 /// ```
201 ///
202 /// For these equation to be satisfiable, the types `C1` and `C2`
203 /// can only refer to a limited set of regions. For example, `C1`
204 /// can only refer to `'static` and `'a`, and `C2` can only refer
205 /// to `'static` and `'b`. The job of this function is to impose that
206 /// constraint.
207 ///
208 /// Up to this point, C1 and C2 are basically just random type
209 /// inference variables, and hence they may contain arbitrary
210 /// regions. In fact, it is fairly likely that they do! Consider
211 /// this possible definition of `foo`:
212 ///
213 /// ```text
214 /// fn foo<'a, 'b>(x: &'a i32, y: &'b i32) -> (impl Bar<'a>, impl Bar<'b>) {
215 /// (&*x, &*y)
216 /// }
217 /// ```
218 ///
219 /// Here, the values for the concrete types of the two impl
220 /// traits will include inference variables:
221 ///
222 /// ```text
223 /// &'0 i32
224 /// &'1 i32
225 /// ```
226 ///
227 /// Ordinarily, the subtyping rules would ensure that these are
228 /// sufficiently large. But since `impl Bar<'a>` isn't a specific
9fa01778 229 /// type per se, we don't get such constraints by default. This
ff7c6d11
XL
230 /// is where this function comes into play. It adds extra
231 /// constraints to ensure that all the regions which appear in the
232 /// inferred type are regions that could validly appear.
233 ///
234 /// This is actually a bit of a tricky constraint in general. We
235 /// want to say that each variable (e.g., `'0`) can only take on
416331ca 236 /// values that were supplied as arguments to the opaque type
ff7c6d11
XL
237 /// (e.g., `'a` for `Foo1<'a>`) or `'static`, which is always in
238 /// scope. We don't have a constraint quite of this kind in the current
239 /// region checker.
240 ///
241 /// # The Solution
242 ///
dc9dc135
XL
243 /// We generally prefer to make `<=` constraints, since they
244 /// integrate best into the region solver. To do that, we find the
245 /// "minimum" of all the arguments that appear in the substs: that
246 /// is, some region which is less than all the others. In the case
247 /// of `Foo1<'a>`, that would be `'a` (it's the only choice, after
248 /// all). Then we apply that as a least bound to the variables
249 /// (e.g., `'a <= '0`).
ff7c6d11
XL
250 ///
251 /// In some cases, there is no minimum. Consider this example:
252 ///
253 /// ```text
254 /// fn baz<'a, 'b>() -> impl Trait<'a, 'b> { ... }
255 /// ```
256 ///
dc9dc135
XL
257 /// Here we would report a more complex "in constraint", like `'r
258 /// in ['a, 'b, 'static]` (where `'r` is some regon appearing in
259 /// the hidden type).
260 ///
261 /// # Constrain regions, not the hidden concrete type
262 ///
263 /// Note that generating constraints on each region `Rc` is *not*
264 /// the same as generating an outlives constraint on `Tc` iself.
265 /// For example, if we had a function like this:
266 ///
267 /// ```rust
268 /// fn foo<'a, T>(x: &'a u32, y: T) -> impl Foo<'a> {
269 /// (x, y)
270 /// }
271 ///
272 /// // Equivalent to:
416331ca 273 /// type FooReturn<'a, T> = impl Foo<'a>;
dc9dc135
XL
274 /// fn foo<'a, T>(..) -> FooReturn<'a, T> { .. }
275 /// ```
276 ///
277 /// then the hidden type `Tc` would be `(&'0 u32, T)` (where `'0`
278 /// is an inference variable). If we generated a constraint that
279 /// `Tc: 'a`, then this would incorrectly require that `T: 'a` --
416331ca 280 /// but this is not necessary, because the opaque type we
dc9dc135
XL
281 /// create will be allowed to reference `T`. So we only generate a
282 /// constraint that `'0: 'a`.
ff7c6d11
XL
283 ///
284 /// # The `free_region_relations` parameter
285 ///
286 /// The `free_region_relations` argument is used to find the
416331ca 287 /// "minimum" of the regions supplied to a given opaque type.
ff7c6d11
XL
288 /// It must be a relation that can answer whether `'a <= 'b`,
289 /// where `'a` and `'b` are regions that appear in the "substs"
416331ca 290 /// for the opaque type references (the `<'a>` in `Foo1<'a>`).
ff7c6d11
XL
291 ///
292 /// Note that we do not impose the constraints based on the
293 /// generic regions from the `Foo1` definition (e.g., `'x`). This
294 /// is because the constraints we are imposing here is basically
295 /// the concern of the one generating the constraining type C1,
296 /// which is the current function. It also means that we can
297 /// take "implied bounds" into account in some cases:
298 ///
299 /// ```text
300 /// trait SomeTrait<'a, 'b> { }
301 /// fn foo<'a, 'b>(_: &'a &'b u32) -> impl SomeTrait<'a, 'b> { .. }
302 /// ```
303 ///
304 /// Here, the fact that `'b: 'a` is known only because of the
305 /// implied bounds from the `&'a &'b u32` parameter, and is not
416331ca 306 /// "inherent" to the opaque type definition.
ff7c6d11
XL
307 ///
308 /// # Parameters
309 ///
b7449926 310 /// - `opaque_types` -- the map produced by `instantiate_opaque_types`
ff7c6d11
XL
311 /// - `free_region_relations` -- something that can be used to relate
312 /// the free regions (`'a`) that appear in the impl trait.
b7449926 313 pub fn constrain_opaque_types<FRR: FreeRegionRelations<'tcx>>(
ff7c6d11 314 &self,
b7449926 315 opaque_types: &OpaqueTypeMap<'tcx>,
ff7c6d11
XL
316 free_region_relations: &FRR,
317 ) {
b7449926 318 debug!("constrain_opaque_types()");
ff7c6d11 319
b7449926
XL
320 for (&def_id, opaque_defn) in opaque_types {
321 self.constrain_opaque_type(def_id, opaque_defn, free_region_relations);
ff7c6d11
XL
322 }
323 }
324
dc9dc135 325 /// See `constrain_opaque_types` for documentation.
0bf4aa26 326 pub fn constrain_opaque_type<FRR: FreeRegionRelations<'tcx>>(
ff7c6d11
XL
327 &self,
328 def_id: DefId,
b7449926 329 opaque_defn: &OpaqueTypeDecl<'tcx>,
ff7c6d11
XL
330 free_region_relations: &FRR,
331 ) {
b7449926
XL
332 debug!("constrain_opaque_type()");
333 debug!("constrain_opaque_type: def_id={:?}", def_id);
334 debug!("constrain_opaque_type: opaque_defn={:#?}", opaque_defn);
ff7c6d11 335
48663c56
XL
336 let tcx = self.tcx;
337
dc9dc135 338 let concrete_ty = self.resolve_vars_if_possible(&opaque_defn.concrete_ty);
ff7c6d11 339
b7449926 340 debug!("constrain_opaque_type: concrete_ty={:?}", concrete_ty);
ff7c6d11 341
dc9dc135 342 let opaque_type_generics = tcx.generics_of(def_id);
ff7c6d11 343
48663c56 344 let span = tcx.def_span(def_id);
ff7c6d11 345
48663c56 346 // If there are required region bounds, we can use them.
b7449926 347 if opaque_defn.has_required_region_bounds {
48663c56 348 let predicates_of = tcx.predicates_of(def_id);
dc9dc135 349 debug!("constrain_opaque_type: predicates: {:#?}", predicates_of,);
48663c56
XL
350 let bounds = predicates_of.instantiate(tcx, opaque_defn.substs);
351 debug!("constrain_opaque_type: bounds={:#?}", bounds);
352 let opaque_type = tcx.mk_opaque(def_id, opaque_defn.substs);
353
dc9dc135 354 let required_region_bounds = tcx.required_region_bounds(opaque_type, bounds.predicates);
48663c56
XL
355 debug_assert!(!required_region_bounds.is_empty());
356
dc9dc135
XL
357 for required_region in required_region_bounds {
358 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
359 tcx: self.tcx,
360 op: |r| self.sub_regions(infer::CallReturn(span), required_region, r),
48663c56
XL
361 });
362 }
ff7c6d11
XL
363 return;
364 }
365
366 // There were no `required_region_bounds`,
367 // so we have to search for a `least_region`.
368 // Go through all the regions used as arguments to the
416331ca 369 // opaque type. These are the parameters to the opaque
ff7c6d11
XL
370 // type; so in our example above, `substs` would contain
371 // `['a]` for the first impl trait and `'b` for the
372 // second.
373 let mut least_region = None;
dc9dc135 374 for param in &opaque_type_generics.params {
94b46f34
XL
375 match param.kind {
376 GenericParamDefKind::Lifetime => {}
dc9dc135 377 _ => continue,
94b46f34 378 }
dc9dc135 379
ff7c6d11 380 // Get the value supplied for this region from the substs.
b7449926 381 let subst_arg = opaque_defn.substs.region_at(param.index as usize);
ff7c6d11
XL
382
383 // Compute the least upper bound of it with the other regions.
b7449926
XL
384 debug!("constrain_opaque_types: least_region={:?}", least_region);
385 debug!("constrain_opaque_types: subst_arg={:?}", subst_arg);
ff7c6d11
XL
386 match least_region {
387 None => least_region = Some(subst_arg),
388 Some(lr) => {
389 if free_region_relations.sub_free_regions(lr, subst_arg) {
390 // keep the current least region
391 } else if free_region_relations.sub_free_regions(subst_arg, lr) {
392 // switch to `subst_arg`
393 least_region = Some(subst_arg);
394 } else {
395 // There are two regions (`lr` and
dc9dc135
XL
396 // `subst_arg`) which are not relatable. We
397 // can't find a best choice. Therefore,
398 // instead of creating a single bound like
399 // `'r: 'a` (which is our preferred choice),
400 // we will create a "in bound" like `'r in
401 // ['a, 'b, 'c]`, where `'a..'c` are the
402 // regions that appear in the impl trait.
403 return self.generate_member_constraint(
404 concrete_ty,
405 opaque_type_generics,
406 opaque_defn,
407 def_id,
408 lr,
409 subst_arg,
410 );
ff7c6d11
XL
411 }
412 }
413 }
414 }
415
48663c56 416 let least_region = least_region.unwrap_or(tcx.lifetimes.re_static);
b7449926 417 debug!("constrain_opaque_types: least_region={:?}", least_region);
ff7c6d11 418
dc9dc135
XL
419 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
420 tcx: self.tcx,
421 op: |r| self.sub_regions(infer::CallReturn(span), least_region, r),
48663c56 422 });
ff7c6d11
XL
423 }
424
dc9dc135
XL
425 /// As a fallback, we sometimes generate an "in constraint". For
426 /// a case like `impl Foo<'a, 'b>`, where `'a` and `'b` cannot be
427 /// related, we would generate a constraint `'r in ['a, 'b,
428 /// 'static]` for each region `'r` that appears in the hidden type
429 /// (i.e., it must be equal to `'a`, `'b`, or `'static`).
430 ///
431 /// `conflict1` and `conflict2` are the two region bounds that we
432 /// detected which were unrelated. They are used for diagnostics.
433 fn generate_member_constraint(
434 &self,
435 concrete_ty: Ty<'tcx>,
436 opaque_type_generics: &ty::Generics,
437 opaque_defn: &OpaqueTypeDecl<'tcx>,
438 opaque_type_def_id: DefId,
439 conflict1: ty::Region<'tcx>,
440 conflict2: ty::Region<'tcx>,
441 ) {
442 // For now, enforce a feature gate outside of async functions.
443 if self.member_constraint_feature_gate(
444 opaque_defn,
445 opaque_type_def_id,
446 conflict1,
447 conflict2,
448 ) {
449 return;
450 }
451
452 // Create the set of choice regions: each region in the hidden
453 // type can be equal to any of the region parameters of the
454 // opaque type definition.
455 let choice_regions: Lrc<Vec<ty::Region<'tcx>>> = Lrc::new(
456 opaque_type_generics
457 .params
458 .iter()
459 .filter(|param| match param.kind {
460 GenericParamDefKind::Lifetime => true,
461 GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => false,
462 })
463 .map(|param| opaque_defn.substs.region_at(param.index as usize))
464 .chain(std::iter::once(self.tcx.lifetimes.re_static))
465 .collect(),
466 );
467
468 concrete_ty.visit_with(&mut ConstrainOpaqueTypeRegionVisitor {
469 tcx: self.tcx,
470 op: |r| self.member_constraint(
471 opaque_type_def_id,
472 opaque_defn.definition_span,
473 concrete_ty,
474 r,
475 &choice_regions,
476 ),
477 });
478 }
479
480 /// Member constraints are presently feature-gated except for
481 /// async-await. We expect to lift this once we've had a bit more
482 /// time.
483 fn member_constraint_feature_gate(
484 &self,
485 opaque_defn: &OpaqueTypeDecl<'tcx>,
486 opaque_type_def_id: DefId,
487 conflict1: ty::Region<'tcx>,
488 conflict2: ty::Region<'tcx>,
489 ) -> bool {
490 // If we have `#![feature(member_constraints)]`, no problems.
491 if self.tcx.features().member_constraints {
492 return false;
493 }
494
495 let span = self.tcx.def_span(opaque_type_def_id);
496
497 // Without a feature-gate, we only generate member-constraints for async-await.
498 let context_name = match opaque_defn.origin {
499 // No feature-gate required for `async fn`.
416331ca 500 hir::OpaqueTyOrigin::AsyncFn => return false,
dc9dc135
XL
501
502 // Otherwise, generate the label we'll use in the error message.
416331ca
XL
503 hir::OpaqueTyOrigin::TypeAlias => "impl Trait",
504 hir::OpaqueTyOrigin::FnReturn => "impl Trait",
dc9dc135
XL
505 };
506 let msg = format!("ambiguous lifetime bound in `{}`", context_name);
507 let mut err = self.tcx.sess.struct_span_err(span, &msg);
508
509 let conflict1_name = conflict1.to_string();
510 let conflict2_name = conflict2.to_string();
511 let label_owned;
512 let label = match (&*conflict1_name, &*conflict2_name) {
513 ("'_", "'_") => "the elided lifetimes here do not outlive one another",
514 _ => {
515 label_owned = format!(
516 "neither `{}` nor `{}` outlives the other",
517 conflict1_name, conflict2_name,
518 );
519 &label_owned
520 }
521 };
522 err.span_label(span, label);
523
524 if nightly_options::is_nightly_build() {
525 help!(err,
526 "add #![feature(member_constraints)] to the crate attributes \
527 to enable");
528 }
529
530 err.emit();
531 true
532 }
533
b7449926 534 /// Given the fully resolved, instantiated type for an opaque
ff7c6d11 535 /// type, i.e., the value of an inference variable like C1 or C2
416331ca 536 /// (*), computes the "definition type" for an opaque type
ff7c6d11
XL
537 /// definition -- that is, the inferred value of `Foo1<'x>` or
538 /// `Foo2<'x>` that we would conceptually use in its definition:
539 ///
416331ca
XL
540 /// type Foo1<'x> = impl Bar<'x> = AAA; <-- this type AAA
541 /// type Foo2<'x> = impl Bar<'x> = BBB; <-- or this type BBB
ff7c6d11
XL
542 /// fn foo<'a, 'b>(..) -> (Foo1<'a>, Foo2<'b>) { .. }
543 ///
544 /// Note that these values are defined in terms of a distinct set of
545 /// generic parameters (`'x` instead of `'a`) from C1 or C2. The main
546 /// purpose of this function is to do that translation.
547 ///
548 /// (*) C1 and C2 were introduced in the comments on
b7449926 549 /// `constrain_opaque_types`. Read that comment for more context.
ff7c6d11
XL
550 ///
551 /// # Parameters
552 ///
553 /// - `def_id`, the `impl Trait` type
b7449926 554 /// - `opaque_defn`, the opaque definition created in `instantiate_opaque_types`
ff7c6d11 555 /// - `instantiated_ty`, the inferred type C1 -- fully resolved, lifted version of
b7449926
XL
556 /// `opaque_defn.concrete_ty`
557 pub fn infer_opaque_definition_from_instantiation(
ff7c6d11
XL
558 &self,
559 def_id: DefId,
b7449926 560 opaque_defn: &OpaqueTypeDecl<'tcx>,
dc9dc135 561 instantiated_ty: Ty<'tcx>,
416331ca 562 span: Span,
dc9dc135 563 ) -> Ty<'tcx> {
ff7c6d11 564 debug!(
b7449926 565 "infer_opaque_definition_from_instantiation(def_id={:?}, instantiated_ty={:?})",
8faf50e0 566 def_id, instantiated_ty
ff7c6d11
XL
567 );
568
ff7c6d11
XL
569 // Use substs to build up a reverse map from regions to their
570 // identity mappings. This is necessary because of `impl
571 // Trait` lifetimes are computed by replacing existing
572 // lifetimes with 'static and remapping only those used in the
573 // `impl Trait` return type, resulting in the parameters
574 // shifting.
e74abb32
XL
575 let id_substs = InternalSubsts::identity_for_item(self.tcx, def_id);
576 let map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>> = opaque_defn
ff7c6d11
XL
577 .substs
578 .iter()
579 .enumerate()
580 .map(|(index, subst)| (*subst, id_substs[index]))
581 .collect();
582
583 // Convert the type from the function into a type valid outside
584 // the function, by replacing invalid regions with 'static,
585 // after producing an error for each of them.
dc9dc135
XL
586 let definition_ty = instantiated_ty.fold_with(&mut ReverseMapper::new(
587 self.tcx,
588 self.is_tainted_by_errors(),
589 def_id,
590 map,
591 instantiated_ty,
416331ca 592 span,
dc9dc135
XL
593 ));
594 debug!("infer_opaque_definition_from_instantiation: definition_ty={:?}", definition_ty);
0531ce1d 595
ff7c6d11
XL
596 definition_ty
597 }
598}
599
dc9dc135
XL
600pub fn unexpected_hidden_region_diagnostic(
601 tcx: TyCtxt<'tcx>,
602 region_scope_tree: Option<&region::ScopeTree>,
603 opaque_type_def_id: DefId,
604 hidden_ty: Ty<'tcx>,
605 hidden_region: ty::Region<'tcx>,
606) -> DiagnosticBuilder<'tcx> {
607 let span = tcx.def_span(opaque_type_def_id);
608 let mut err = struct_span_err!(
609 tcx.sess,
610 span,
611 E0700,
612 "hidden type for `impl Trait` captures lifetime that does not appear in bounds",
613 );
614
615 // Explain the region we are capturing.
616 if let ty::ReEarlyBound(_) | ty::ReFree(_) | ty::ReStatic | ty::ReEmpty = hidden_region {
617 // Assuming regionck succeeded (*), we ought to always be
618 // capturing *some* region from the fn header, and hence it
619 // ought to be free. So under normal circumstances, we will go
620 // down this path which gives a decent human readable
621 // explanation.
622 //
623 // (*) if not, the `tainted_by_errors` flag would be set to
624 // true in any case, so we wouldn't be here at all.
625 tcx.note_and_explain_free_region(
626 &mut err,
627 &format!("hidden type `{}` captures ", hidden_ty),
628 hidden_region,
629 "",
630 );
631 } else {
632 // Ugh. This is a painful case: the hidden region is not one
633 // that we can easily summarize or explain. This can happen
634 // in a case like
635 // `src/test/ui/multiple-lifetimes/ordinary-bounds-unsuited.rs`:
636 //
637 // ```
638 // fn upper_bounds<'a, 'b>(a: Ordinary<'a>, b: Ordinary<'b>) -> impl Trait<'a, 'b> {
639 // if condition() { a } else { b }
640 // }
641 // ```
642 //
643 // Here the captured lifetime is the intersection of `'a` and
644 // `'b`, which we can't quite express.
645
646 if let Some(region_scope_tree) = region_scope_tree {
647 // If the `region_scope_tree` is available, this is being
648 // invoked from the "region inferencer error". We can at
649 // least report a really cryptic error for now.
650 tcx.note_and_explain_region(
651 region_scope_tree,
652 &mut err,
653 &format!("hidden type `{}` captures ", hidden_ty),
654 hidden_region,
655 "",
656 );
657 } else {
658 // If the `region_scope_tree` is *unavailable*, this is
659 // being invoked by the code that comes *after* region
660 // inferencing. This is a bug, as the region inferencer
661 // ought to have noticed the failed constraint and invoked
662 // error reporting, which in turn should have prevented us
663 // from getting trying to infer the hidden type
664 // completely.
665 tcx.sess.delay_span_bug(
666 span,
667 &format!(
668 "hidden type captures unexpected lifetime `{:?}` \
669 but no region inference failure",
670 hidden_region,
671 ),
672 );
673 }
674 }
675
676 err
677}
678
48663c56
XL
679// Visitor that requires that (almost) all regions in the type visited outlive
680// `least_region`. We cannot use `push_outlives_components` because regions in
681// closure signatures are not included in their outlives components. We need to
682// ensure all regions outlive the given bound so that we don't end up with,
683// say, `ReScope` appearing in a return type and causing ICEs when other
684// functions end up with region constraints involving regions from other
685// functions.
686//
687// We also cannot use `for_each_free_region` because for closures it includes
688// the regions parameters from the enclosing item.
689//
690// We ignore any type parameters because impl trait values are assumed to
691// capture all the in-scope type parameters.
dc9dc135
XL
692struct ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
693where
694 OP: FnMut(ty::Region<'tcx>),
695{
696 tcx: TyCtxt<'tcx>,
697 op: OP,
48663c56
XL
698}
699
dc9dc135
XL
700impl<'tcx, OP> TypeVisitor<'tcx> for ConstrainOpaqueTypeRegionVisitor<'tcx, OP>
701where
702 OP: FnMut(ty::Region<'tcx>),
48663c56
XL
703{
704 fn visit_binder<T: TypeFoldable<'tcx>>(&mut self, t: &ty::Binder<T>) -> bool {
705 t.skip_binder().visit_with(self);
706 false // keep visiting
707 }
708
709 fn visit_region(&mut self, r: ty::Region<'tcx>) -> bool {
710 match *r {
711 // ignore bound regions, keep visiting
712 ty::ReLateBound(_, _) => false,
713 _ => {
dc9dc135 714 (self.op)(r);
48663c56
XL
715 false
716 }
717 }
718 }
719
720 fn visit_ty(&mut self, ty: Ty<'tcx>) -> bool {
721 // We're only interested in types involving regions
722 if !ty.flags.intersects(ty::TypeFlags::HAS_FREE_REGIONS) {
723 return false; // keep visiting
724 }
725
e74abb32 726 match ty.kind {
48663c56
XL
727 ty::Closure(def_id, ref substs) => {
728 // Skip lifetime parameters of the enclosing item(s)
729
e74abb32 730 for upvar_ty in substs.as_closure().upvar_tys(def_id, self.tcx) {
48663c56
XL
731 upvar_ty.visit_with(self);
732 }
733
e74abb32 734 substs.as_closure().sig_ty(def_id, self.tcx).visit_with(self);
48663c56
XL
735 }
736
737 ty::Generator(def_id, ref substs, _) => {
738 // Skip lifetime parameters of the enclosing item(s)
739 // Also skip the witness type, because that has no free regions.
740
e74abb32 741 for upvar_ty in substs.as_generator().upvar_tys(def_id, self.tcx) {
48663c56
XL
742 upvar_ty.visit_with(self);
743 }
744
e74abb32
XL
745 substs.as_generator().return_ty(def_id, self.tcx).visit_with(self);
746 substs.as_generator().yield_ty(def_id, self.tcx).visit_with(self);
48663c56
XL
747 }
748 _ => {
749 ty.super_visit_with(self);
750 }
751 }
752
753 false
754 }
755}
756
dc9dc135
XL
757struct ReverseMapper<'tcx> {
758 tcx: TyCtxt<'tcx>,
0531ce1d
XL
759
760 /// If errors have already been reported in this fn, we suppress
761 /// our own errors because they are sometimes derivative.
762 tainted_by_errors: bool,
763
b7449926 764 opaque_type_def_id: DefId,
e74abb32 765 map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>,
0531ce1d
XL
766 map_missing_regions_to_empty: bool,
767
768 /// initially `Some`, set to `None` once error has been reported
769 hidden_ty: Option<Ty<'tcx>>,
416331ca
XL
770
771 /// Span of function being checked.
772 span: Span,
0531ce1d
XL
773}
774
dc9dc135 775impl ReverseMapper<'tcx> {
0531ce1d 776 fn new(
dc9dc135 777 tcx: TyCtxt<'tcx>,
0531ce1d 778 tainted_by_errors: bool,
b7449926 779 opaque_type_def_id: DefId,
e74abb32 780 map: FxHashMap<GenericArg<'tcx>, GenericArg<'tcx>>,
0531ce1d 781 hidden_ty: Ty<'tcx>,
416331ca 782 span: Span,
0531ce1d
XL
783 ) -> Self {
784 Self {
785 tcx,
786 tainted_by_errors,
b7449926 787 opaque_type_def_id,
0531ce1d
XL
788 map,
789 map_missing_regions_to_empty: false,
790 hidden_ty: Some(hidden_ty),
416331ca 791 span,
0531ce1d
XL
792 }
793 }
794
e74abb32
XL
795 fn fold_kind_mapping_missing_regions_to_empty(
796 &mut self,
797 kind: GenericArg<'tcx>,
798 ) -> GenericArg<'tcx> {
0531ce1d
XL
799 assert!(!self.map_missing_regions_to_empty);
800 self.map_missing_regions_to_empty = true;
801 let kind = kind.fold_with(self);
802 self.map_missing_regions_to_empty = false;
803 kind
804 }
805
e74abb32 806 fn fold_kind_normally(&mut self, kind: GenericArg<'tcx>) -> GenericArg<'tcx> {
0531ce1d
XL
807 assert!(!self.map_missing_regions_to_empty);
808 kind.fold_with(self)
809 }
810}
811
dc9dc135
XL
812impl TypeFolder<'tcx> for ReverseMapper<'tcx> {
813 fn tcx(&self) -> TyCtxt<'tcx> {
0531ce1d
XL
814 self.tcx
815 }
816
817 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
818 match r {
819 // ignore bound regions that appear in the type (e.g., this
820 // would ignore `'r` in a type like `for<'r> fn(&'r u32)`.
821 ty::ReLateBound(..) |
822
823 // ignore `'static`, as that can appear anywhere
48663c56 824 ty::ReStatic => return r,
0531ce1d
XL
825
826 _ => { }
827 }
828
416331ca 829 let generics = self.tcx().generics_of(self.opaque_type_def_id);
0531ce1d 830 match self.map.get(&r.into()).map(|k| k.unpack()) {
e74abb32 831 Some(GenericArgKind::Lifetime(r1)) => r1,
0531ce1d 832 Some(u) => panic!("region mapped to unexpected kind: {:?}", u),
416331ca 833 None if generics.parent.is_some() => {
0531ce1d
XL
834 if !self.map_missing_regions_to_empty && !self.tainted_by_errors {
835 if let Some(hidden_ty) = self.hidden_ty.take() {
dc9dc135
XL
836 unexpected_hidden_region_diagnostic(
837 self.tcx,
838 None,
839 self.opaque_type_def_id,
840 hidden_ty,
0531ce1d 841 r,
dc9dc135 842 ).emit();
0531ce1d
XL
843 }
844 }
48663c56 845 self.tcx.lifetimes.re_empty
dc9dc135 846 }
416331ca
XL
847 None => {
848 self.tcx.sess
849 .struct_span_err(
850 self.span,
851 "non-defining opaque type use in defining scope"
852 )
853 .span_label(
854 self.span,
855 format!("lifetime `{}` is part of concrete type but not used in \
856 parameter list of the `impl Trait` type alias", r),
857 )
858 .emit();
859
e74abb32 860 self.tcx().mk_region(ty::ReStatic)
416331ca 861 },
0531ce1d
XL
862 }
863 }
864
865 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
e74abb32 866 match ty.kind {
b7449926 867 ty::Closure(def_id, substs) => {
0531ce1d
XL
868 // I am a horrible monster and I pray for death. When
869 // we encounter a closure here, it is always a closure
870 // from within the function that we are currently
871 // type-checking -- one that is now being encapsulated
416331ca 872 // in an opaque type. Ideally, we would
0531ce1d
XL
873 // go through the types/lifetimes that it references
874 // and treat them just like we would any other type,
875 // which means we would error out if we find any
876 // reference to a type/region that is not in the
877 // "reverse map".
878 //
879 // **However,** in the case of closures, there is a
880 // somewhat subtle (read: hacky) consideration. The
881 // problem is that our closure types currently include
882 // all the lifetime parameters declared on the
883 // enclosing function, even if they are unused by the
884 // closure itself. We can't readily filter them out,
885 // so here we replace those values with `'empty`. This
886 // can't really make a difference to the rest of the
887 // compiler; those regions are ignored for the
888 // outlives relation, and hence don't affect trait
889 // selection or auto traits, and they are erased
94b46f34 890 // during codegen.
0531ce1d
XL
891
892 let generics = self.tcx.generics_of(def_id);
dc9dc135 893 let substs =
e74abb32 894 self.tcx.mk_substs(substs.iter().enumerate().map(|(index, &kind)| {
94b46f34 895 if index < generics.parent_count {
0531ce1d
XL
896 // Accommodate missing regions in the parent kinds...
897 self.fold_kind_mapping_missing_regions_to_empty(kind)
898 } else {
899 // ...but not elsewhere.
900 self.fold_kind_normally(kind)
901 }
dc9dc135 902 }));
0531ce1d 903
e74abb32 904 self.tcx.mk_closure(def_id, substs)
0531ce1d
XL
905 }
906
48663c56
XL
907 ty::Generator(def_id, substs, movability) => {
908 let generics = self.tcx.generics_of(def_id);
dc9dc135 909 let substs =
e74abb32 910 self.tcx.mk_substs(substs.iter().enumerate().map(|(index, &kind)| {
48663c56
XL
911 if index < generics.parent_count {
912 // Accommodate missing regions in the parent kinds...
913 self.fold_kind_mapping_missing_regions_to_empty(kind)
914 } else {
915 // ...but not elsewhere.
916 self.fold_kind_normally(kind)
917 }
dc9dc135 918 }));
48663c56 919
e74abb32 920 self.tcx.mk_generator(def_id, substs, movability)
48663c56
XL
921 }
922
416331ca
XL
923 ty::Param(..) => {
924 // Look it up in the substitution list.
925 match self.map.get(&ty.into()).map(|k| k.unpack()) {
926 // Found it in the substitution list; replace with the parameter from the
927 // opaque type.
e74abb32 928 Some(GenericArgKind::Type(t1)) => t1,
416331ca
XL
929 Some(u) => panic!("type mapped to unexpected kind: {:?}", u),
930 None => {
931 self.tcx.sess
932 .struct_span_err(
933 self.span,
934 &format!("type parameter `{}` is part of concrete type but not \
935 used in parameter list for the `impl Trait` type alias",
936 ty),
937 )
938 .emit();
939
940 self.tcx().types.err
941 }
942 }
943 }
944
0531ce1d
XL
945 _ => ty.super_fold_with(self),
946 }
947 }
416331ca
XL
948
949 fn fold_const(&mut self, ct: &'tcx ty::Const<'tcx>) -> &'tcx ty::Const<'tcx> {
950 trace!("checking const {:?}", ct);
951 // Find a const parameter
952 match ct.val {
60c5eb7d 953 ty::ConstKind::Param(..) => {
416331ca
XL
954 // Look it up in the substitution list.
955 match self.map.get(&ct.into()).map(|k| k.unpack()) {
956 // Found it in the substitution list, replace with the parameter from the
957 // opaque type.
e74abb32 958 Some(GenericArgKind::Const(c1)) => c1,
416331ca
XL
959 Some(u) => panic!("const mapped to unexpected kind: {:?}", u),
960 None => {
961 self.tcx.sess
962 .struct_span_err(
963 self.span,
964 &format!("const parameter `{}` is part of concrete type but not \
965 used in parameter list for the `impl Trait` type alias",
966 ct)
967 )
968 .emit();
969
970 self.tcx().consts.err
971 }
972 }
973 }
974
975 _ => ct,
976 }
977 }
0531ce1d
XL
978}
979
dc9dc135
XL
980struct Instantiator<'a, 'tcx> {
981 infcx: &'a InferCtxt<'a, 'tcx>,
ff7c6d11 982 parent_def_id: DefId,
9fa01778 983 body_id: hir::HirId,
ff7c6d11 984 param_env: ty::ParamEnv<'tcx>,
dc9dc135 985 value_span: Span,
b7449926 986 opaque_types: OpaqueTypeMap<'tcx>,
ff7c6d11
XL
987 obligations: Vec<PredicateObligation<'tcx>>,
988}
989
dc9dc135 990impl<'a, 'tcx> Instantiator<'a, 'tcx> {
b7449926
XL
991 fn instantiate_opaque_types_in_map<T: TypeFoldable<'tcx>>(&mut self, value: &T) -> T {
992 debug!("instantiate_opaque_types_in_map(value={:?})", value);
ff7c6d11
XL
993 let tcx = self.infcx.tcx;
994 value.fold_with(&mut BottomUpFolder {
995 tcx,
48663c56 996 ty_op: |ty| {
e74abb32
XL
997 if ty.references_error() {
998 return tcx.types.err;
999 } else if let ty::Opaque(def_id, substs) = ty.kind {
ff7c6d11
XL
1000 // Check that this is `impl Trait` type is
1001 // declared by `parent_def_id` -- i.e., one whose
1002 // value we are inferring. At present, this is
1003 // always true during the first phase of
1004 // type-check, but not always true later on during
416331ca 1005 // NLL. Once we support named opaque types more fully,
ff7c6d11
XL
1006 // this same scenario will be able to arise during all phases.
1007 //
416331ca
XL
1008 // Here is an example using type alias `impl Trait`
1009 // that indicates the distinction we are checking for:
ff7c6d11
XL
1010 //
1011 // ```rust
1012 // mod a {
416331ca 1013 // pub type Foo = impl Iterator;
ff7c6d11
XL
1014 // pub fn make_foo() -> Foo { .. }
1015 // }
1016 //
1017 // mod b {
1018 // fn foo() -> a::Foo { a::make_foo() }
1019 // }
1020 // ```
1021 //
1022 // Here, the return type of `foo` references a
b7449926 1023 // `Opaque` indeed, but not one whose value is
ff7c6d11
XL
1024 // presently being inferred. You can get into a
1025 // similar situation with closure return types
1026 // today:
1027 //
1028 // ```rust
1029 // fn foo() -> impl Iterator { .. }
1030 // fn bar() {
b7449926 1031 // let x = || foo(); // returns the Opaque assoc with `foo`
ff7c6d11
XL
1032 // }
1033 // ```
532ac7d7 1034 if let Some(opaque_hir_id) = tcx.hir().as_local_hir_id(def_id) {
8faf50e0
XL
1035 let parent_def_id = self.parent_def_id;
1036 let def_scope_default = || {
532ac7d7 1037 let opaque_parent_hir_id = tcx.hir().get_parent_item(opaque_hir_id);
416331ca
XL
1038 parent_def_id == tcx.hir()
1039 .local_def_id(opaque_parent_hir_id)
8faf50e0 1040 };
dc9dc135 1041 let (in_definition_scope, origin) = match tcx.hir().find(opaque_hir_id) {
e74abb32 1042 Some(Node::Item(item)) => match item.kind {
dc9dc135 1043 // Anonymous `impl Trait`
416331ca 1044 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
8faf50e0 1045 impl_trait_fn: Some(parent),
532ac7d7 1046 origin,
8faf50e0 1047 ..
532ac7d7 1048 }) => (parent == self.parent_def_id, origin),
416331ca
XL
1049 // Named `type Foo = impl Bar;`
1050 hir::ItemKind::OpaqueTy(hir::OpaqueTy {
8faf50e0 1051 impl_trait_fn: None,
532ac7d7 1052 origin,
8faf50e0 1053 ..
532ac7d7 1054 }) => (
416331ca 1055 may_define_opaque_type(
532ac7d7
XL
1056 tcx,
1057 self.parent_def_id,
1058 opaque_hir_id,
1059 ),
1060 origin,
8faf50e0 1061 ),
416331ca
XL
1062 _ => {
1063 (def_scope_default(), hir::OpaqueTyOrigin::TypeAlias)
1064 }
8faf50e0 1065 },
e74abb32 1066 Some(Node::ImplItem(item)) => match item.kind {
416331ca
XL
1067 hir::ImplItemKind::OpaqueTy(_) => (
1068 may_define_opaque_type(
532ac7d7
XL
1069 tcx,
1070 self.parent_def_id,
1071 opaque_hir_id,
1072 ),
416331ca 1073 hir::OpaqueTyOrigin::TypeAlias,
8faf50e0 1074 ),
416331ca
XL
1075 _ => {
1076 (def_scope_default(), hir::OpaqueTyOrigin::TypeAlias)
1077 }
94b46f34 1078 },
8faf50e0
XL
1079 _ => bug!(
1080 "expected (impl) item, found {}",
dc9dc135 1081 tcx.hir().node_to_string(opaque_hir_id),
8faf50e0 1082 ),
94b46f34 1083 };
8faf50e0 1084 if in_definition_scope {
532ac7d7 1085 return self.fold_opaque_ty(ty, def_id, substs, origin);
ff7c6d11
XL
1086 }
1087
0531ce1d 1088 debug!(
b7449926 1089 "instantiate_opaque_types_in_map: \
0bf4aa26 1090 encountered opaque outside its definition scope \
8faf50e0
XL
1091 def_id={:?}",
1092 def_id,
0531ce1d 1093 );
ff7c6d11
XL
1094 }
1095 }
1096
1097 ty
1098 },
48663c56
XL
1099 lt_op: |lt| lt,
1100 ct_op: |ct| ct,
ff7c6d11
XL
1101 })
1102 }
1103
b7449926 1104 fn fold_opaque_ty(
ff7c6d11
XL
1105 &mut self,
1106 ty: Ty<'tcx>,
1107 def_id: DefId,
532ac7d7 1108 substs: SubstsRef<'tcx>,
416331ca 1109 origin: hir::OpaqueTyOrigin,
ff7c6d11
XL
1110 ) -> Ty<'tcx> {
1111 let infcx = self.infcx;
1112 let tcx = infcx.tcx;
1113
dc9dc135 1114 debug!("instantiate_opaque_types: Opaque(def_id={:?}, substs={:?})", def_id, substs);
ff7c6d11 1115
dc9dc135 1116 // Use the same type variable if the exact same opaque type appears more
0731742a 1117 // than once in the return type (e.g., if it's passed to a type alias).
b7449926 1118 if let Some(opaque_defn) = self.opaque_types.get(&def_id) {
e1599b0c 1119 debug!("instantiate_opaque_types: returning concrete ty {:?}", opaque_defn.concrete_ty);
b7449926 1120 return opaque_defn.concrete_ty;
ff7c6d11
XL
1121 }
1122 let span = tcx.def_span(def_id);
e1599b0c 1123 debug!("fold_opaque_ty {:?} {:?}", self.value_span, span);
dc9dc135
XL
1124 let ty_var = infcx
1125 .next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::TypeInference, span });
ff7c6d11
XL
1126
1127 let predicates_of = tcx.predicates_of(def_id);
dc9dc135 1128 debug!("instantiate_opaque_types: predicates={:#?}", predicates_of,);
ff7c6d11 1129 let bounds = predicates_of.instantiate(tcx, substs);
416331ca
XL
1130
1131 let param_env = tcx.param_env(def_id);
1132 let InferOk { value: bounds, obligations } =
1133 infcx.partially_normalize_associated_types_in(span, self.body_id, param_env, &bounds);
1134 self.obligations.extend(obligations);
1135
b7449926 1136 debug!("instantiate_opaque_types: bounds={:?}", bounds);
ff7c6d11
XL
1137
1138 let required_region_bounds = tcx.required_region_bounds(ty, bounds.predicates.clone());
dc9dc135 1139 debug!("instantiate_opaque_types: required_region_bounds={:?}", required_region_bounds);
ff7c6d11 1140
dc9dc135 1141 // Make sure that we are in fact defining the *entire* type
416331ca 1142 // (e.g., `type Foo<T: Bound> = impl Bar;` needs to be
dc9dc135
XL
1143 // defined by a function like `fn foo<T: Bound>() -> Foo<T>`).
1144 debug!("instantiate_opaque_types: param_env={:#?}", self.param_env,);
1145 debug!("instantiate_opaque_types: generics={:#?}", tcx.generics_of(def_id),);
1146
1147 // Ideally, we'd get the span where *this specific `ty` came
1148 // from*, but right now we just use the span from the overall
1149 // value being folded. In simple cases like `-> impl Foo`,
1150 // these are the same span, but not in cases like `-> (impl
1151 // Foo, impl Bar)`.
1152 let definition_span = self.value_span;
8faf50e0 1153
b7449926 1154 self.opaque_types.insert(
ff7c6d11 1155 def_id,
b7449926 1156 OpaqueTypeDecl {
60c5eb7d 1157 opaque_type: ty,
ff7c6d11 1158 substs,
dc9dc135 1159 definition_span,
ff7c6d11
XL
1160 concrete_ty: ty_var,
1161 has_required_region_bounds: !required_region_bounds.is_empty(),
532ac7d7 1162 origin,
ff7c6d11
XL
1163 },
1164 );
b7449926 1165 debug!("instantiate_opaque_types: ty_var={:?}", ty_var);
ff7c6d11 1166
e74abb32
XL
1167 for predicate in &bounds.predicates {
1168 if let ty::Predicate::Projection(projection) = &predicate {
1169 if projection.skip_binder().ty.references_error() {
1170 // No point on adding these obligations since there's a type error involved.
1171 return ty_var;
1172 }
1173 }
1174 }
1175
0bf4aa26 1176 self.obligations.reserve(bounds.predicates.len());
ff7c6d11
XL
1177 for predicate in bounds.predicates {
1178 // Change the predicate to refer to the type variable,
0bf4aa26
XL
1179 // which will be the concrete type instead of the opaque type.
1180 // This also instantiates nested instances of `impl Trait`.
b7449926 1181 let predicate = self.instantiate_opaque_types_in_map(&predicate);
ff7c6d11
XL
1182
1183 let cause = traits::ObligationCause::new(span, self.body_id, traits::SizedReturnType);
1184
1185 // Require that the predicate holds for the concrete type.
b7449926 1186 debug!("instantiate_opaque_types: predicate={:?}", predicate);
dc9dc135 1187 self.obligations.push(traits::Obligation::new(cause, self.param_env, predicate));
ff7c6d11
XL
1188 }
1189
1190 ty_var
1191 }
1192}
8faf50e0 1193
dc9dc135 1194/// Returns `true` if `opaque_hir_id` is a sibling or a child of a sibling of `def_id`.
8faf50e0 1195///
dc9dc135 1196/// Example:
8faf50e0
XL
1197/// ```rust
1198/// pub mod foo {
1199/// pub mod bar {
416331ca
XL
1200/// pub trait Bar { .. }
1201///
1202/// pub type Baz = impl Bar;
8faf50e0
XL
1203///
1204/// fn f1() -> Baz { .. }
1205/// }
1206///
1207/// fn f2() -> bar::Baz { .. }
1208/// }
1209/// ```
1210///
416331ca
XL
1211/// Here, `def_id` is the `DefId` of the defining use of the opaque type (e.g., `f1` or `f2`),
1212/// and `opaque_hir_id` is the `HirId` of the definition of the opaque type `Baz`.
dc9dc135 1213/// For the above example, this function returns `true` for `f1` and `false` for `f2`.
416331ca 1214pub fn may_define_opaque_type(
dc9dc135 1215 tcx: TyCtxt<'_>,
8faf50e0 1216 def_id: DefId,
532ac7d7 1217 opaque_hir_id: hir::HirId,
8faf50e0 1218) -> bool {
dc9dc135 1219 let mut hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
dc9dc135 1220
416331ca 1221 // Named opaque types can be defined by any siblings or children of siblings.
e74abb32 1222 let scope = tcx.hir().get_defining_scope(opaque_hir_id);
dc9dc135
XL
1223 // We walk up the node tree until we hit the root or the scope of the opaque type.
1224 while hir_id != scope && hir_id != hir::CRATE_HIR_ID {
532ac7d7 1225 hir_id = tcx.hir().get_parent_item(hir_id);
8faf50e0 1226 }
dc9dc135 1227 // Syntactically, we are allowed to define the concrete type if:
416331ca
XL
1228 let res = hir_id == scope;
1229 trace!(
1230 "may_define_opaque_type(def={:?}, opaque_node={:?}) = {}",
1231 tcx.hir().get(hir_id),
1232 tcx.hir().get(opaque_hir_id),
1233 res
1234 );
1235 res
8faf50e0 1236}