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