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