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