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