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