]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/closure.rs
Rollup merge of #92715 - chordtoll:empty-string, r=davidtwco
[rust.git] / compiler / rustc_typeck / src / check / closure.rs
1 //! Code for type-checking closure expressions.
2
3 use super::{check_fn, Expectation, FnCtxt, GeneratorTypes};
4
5 use crate::astconv::AstConv;
6 use crate::rustc_middle::ty::subst::Subst;
7 use hir::OpaqueTyOrigin;
8 use rustc_hir as hir;
9 use rustc_hir::def_id::DefId;
10 use rustc_hir::lang_items::LangItem;
11 use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
12 use rustc_infer::infer::LateBoundRegionConversionTime;
13 use rustc_infer::infer::{InferOk, InferResult};
14 use rustc_infer::traits::ObligationCause;
15 use rustc_middle::ty::fold::TypeFoldable;
16 use rustc_middle::ty::subst::InternalSubsts;
17 use rustc_middle::ty::{self, Ty};
18 use rustc_span::source_map::Span;
19 use rustc_span::DUMMY_SP;
20 use rustc_target::spec::abi::Abi;
21 use rustc_trait_selection::traits::error_reporting::ArgKind;
22 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
23 use std::cmp;
24 use std::iter;
25
26 /// What signature do we *expect* the closure to have from context?
27 #[derive(Debug)]
28 struct ExpectedSig<'tcx> {
29     /// Span that gave us this expectation, if we know that.
30     cause_span: Option<Span>,
31     sig: ty::PolyFnSig<'tcx>,
32 }
33
34 struct ClosureSignatures<'tcx> {
35     bound_sig: ty::PolyFnSig<'tcx>,
36     liberated_sig: ty::FnSig<'tcx>,
37 }
38
39 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
40     #[instrument(skip(self, expr, _capture, decl, body_id), level = "debug")]
41     pub fn check_expr_closure(
42         &self,
43         expr: &hir::Expr<'_>,
44         _capture: hir::CaptureBy,
45         decl: &'tcx hir::FnDecl<'tcx>,
46         body_id: hir::BodyId,
47         gen: Option<hir::Movability>,
48         expected: Expectation<'tcx>,
49     ) -> Ty<'tcx> {
50         trace!("decl = {:#?}", decl);
51         trace!("expr = {:#?}", expr);
52
53         // It's always helpful for inference if we know the kind of
54         // closure sooner rather than later, so first examine the expected
55         // type, and see if can glean a closure kind from there.
56         let (expected_sig, expected_kind) = match expected.to_option(self) {
57             Some(ty) => self.deduce_expectations_from_expected_type(ty),
58             None => (None, None),
59         };
60         let body = self.tcx.hir().body(body_id);
61         self.check_closure(expr, expected_kind, decl, body, gen, expected_sig)
62     }
63
64     #[instrument(skip(self, expr, body, decl), level = "debug")]
65     fn check_closure(
66         &self,
67         expr: &hir::Expr<'_>,
68         opt_kind: Option<ty::ClosureKind>,
69         decl: &'tcx hir::FnDecl<'tcx>,
70         body: &'tcx hir::Body<'tcx>,
71         gen: Option<hir::Movability>,
72         expected_sig: Option<ExpectedSig<'tcx>>,
73     ) -> Ty<'tcx> {
74         trace!("decl = {:#?}", decl);
75         let expr_def_id = self.tcx.hir().local_def_id(expr.hir_id);
76         debug!(?expr_def_id);
77
78         let ClosureSignatures { bound_sig, liberated_sig } =
79             self.sig_of_closure(expr.hir_id, expr_def_id.to_def_id(), decl, body, expected_sig);
80
81         debug!(?bound_sig, ?liberated_sig);
82
83         let return_type_pre_known = !liberated_sig.output().is_ty_infer();
84
85         let generator_types = check_fn(
86             self,
87             self.param_env.without_const(),
88             liberated_sig,
89             decl,
90             expr.hir_id,
91             body,
92             gen,
93             return_type_pre_known,
94         )
95         .1;
96
97         let parent_substs = InternalSubsts::identity_for_item(
98             self.tcx,
99             self.tcx.typeck_root_def_id(expr_def_id.to_def_id()),
100         );
101
102         let tupled_upvars_ty = self.infcx.next_ty_var(TypeVariableOrigin {
103             kind: TypeVariableOriginKind::ClosureSynthetic,
104             span: self.tcx.hir().span(expr.hir_id),
105         });
106
107         if let Some(GeneratorTypes { resume_ty, yield_ty, interior, movability }) = generator_types
108         {
109             let generator_substs = ty::GeneratorSubsts::new(
110                 self.tcx,
111                 ty::GeneratorSubstsParts {
112                     parent_substs,
113                     resume_ty,
114                     yield_ty,
115                     return_ty: liberated_sig.output(),
116                     witness: interior,
117                     tupled_upvars_ty,
118                 },
119             );
120
121             return self.tcx.mk_generator(
122                 expr_def_id.to_def_id(),
123                 generator_substs.substs,
124                 movability,
125             );
126         }
127
128         // Tuple up the arguments and insert the resulting function type into
129         // the `closures` table.
130         let sig = bound_sig.map_bound(|sig| {
131             self.tcx.mk_fn_sig(
132                 iter::once(self.tcx.intern_tup(sig.inputs())),
133                 sig.output(),
134                 sig.c_variadic,
135                 sig.unsafety,
136                 sig.abi,
137             )
138         });
139
140         debug!(?sig, ?opt_kind);
141
142         let closure_kind_ty = match opt_kind {
143             Some(kind) => kind.to_ty(self.tcx),
144
145             // Create a type variable (for now) to represent the closure kind.
146             // It will be unified during the upvar inference phase (`upvar.rs`)
147             None => self.infcx.next_ty_var(TypeVariableOrigin {
148                 // FIXME(eddyb) distinguish closure kind inference variables from the rest.
149                 kind: TypeVariableOriginKind::ClosureSynthetic,
150                 span: expr.span,
151             }),
152         };
153
154         let closure_substs = ty::ClosureSubsts::new(
155             self.tcx,
156             ty::ClosureSubstsParts {
157                 parent_substs,
158                 closure_kind_ty,
159                 closure_sig_as_fn_ptr_ty: self.tcx.mk_fn_ptr(sig),
160                 tupled_upvars_ty,
161             },
162         );
163
164         let closure_type = self.tcx.mk_closure(expr_def_id.to_def_id(), closure_substs.substs);
165
166         debug!(?expr.hir_id, ?closure_type);
167
168         closure_type
169     }
170
171     /// Given the expected type, figures out what it can about this closure we
172     /// are about to type check:
173     #[instrument(skip(self), level = "debug")]
174     fn deduce_expectations_from_expected_type(
175         &self,
176         expected_ty: Ty<'tcx>,
177     ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
178         match *expected_ty.kind() {
179             ty::Opaque(def_id, substs) => {
180                 let bounds = self.tcx.explicit_item_bounds(def_id);
181                 let sig = bounds.iter().find_map(|(pred, span)| match pred.kind().skip_binder() {
182                     ty::PredicateKind::Projection(proj_predicate) => self
183                         .deduce_sig_from_projection(
184                             Some(*span),
185                             pred.kind().rebind(proj_predicate.subst(self.tcx, substs)),
186                         ),
187                     _ => None,
188                 });
189
190                 let kind = bounds
191                     .iter()
192                     .filter_map(|(pred, _)| match pred.kind().skip_binder() {
193                         ty::PredicateKind::Trait(tp) => {
194                             self.tcx.fn_trait_kind_from_lang_item(tp.def_id())
195                         }
196                         _ => None,
197                     })
198                     .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
199                 trace!(?sig, ?kind);
200                 (sig, kind)
201             }
202             ty::Dynamic(ref object_type, ..) => {
203                 let sig = object_type.projection_bounds().find_map(|pb| {
204                     let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self);
205                     self.deduce_sig_from_projection(None, pb)
206                 });
207                 let kind = object_type
208                     .principal_def_id()
209                     .and_then(|did| self.tcx.fn_trait_kind_from_lang_item(did));
210                 (sig, kind)
211             }
212             ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid),
213             ty::FnPtr(sig) => {
214                 let expected_sig = ExpectedSig { cause_span: None, sig };
215                 (Some(expected_sig), Some(ty::ClosureKind::Fn))
216             }
217             _ => (None, None),
218         }
219     }
220
221     fn deduce_expectations_from_obligations(
222         &self,
223         expected_vid: ty::TyVid,
224     ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) {
225         let expected_sig =
226             self.obligations_for_self_ty(expected_vid).find_map(|(_, obligation)| {
227                 debug!(?obligation.predicate);
228
229                 let bound_predicate = obligation.predicate.kind();
230                 if let ty::PredicateKind::Projection(proj_predicate) =
231                     obligation.predicate.kind().skip_binder()
232                 {
233                     // Given a Projection predicate, we can potentially infer
234                     // the complete signature.
235                     self.deduce_sig_from_projection(
236                         Some(obligation.cause.span),
237                         bound_predicate.rebind(proj_predicate),
238                     )
239                 } else {
240                     None
241                 }
242             });
243
244         // Even if we can't infer the full signature, we may be able to
245         // infer the kind. This can occur when we elaborate a predicate
246         // like `F : Fn<A>`. Note that due to subtyping we could encounter
247         // many viable options, so pick the most restrictive.
248         let expected_kind = self
249             .obligations_for_self_ty(expected_vid)
250             .filter_map(|(tr, _)| self.tcx.fn_trait_kind_from_lang_item(tr.def_id()))
251             .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur))));
252
253         (expected_sig, expected_kind)
254     }
255
256     /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce
257     /// everything we need to know about a closure or generator.
258     ///
259     /// The `cause_span` should be the span that caused us to
260     /// have this expected signature, or `None` if we can't readily
261     /// know that.
262     fn deduce_sig_from_projection(
263         &self,
264         cause_span: Option<Span>,
265         projection: ty::PolyProjectionPredicate<'tcx>,
266     ) -> Option<ExpectedSig<'tcx>> {
267         let tcx = self.tcx;
268
269         debug!("deduce_sig_from_projection({:?})", projection);
270
271         let trait_def_id = projection.trait_def_id(tcx);
272
273         let is_fn = tcx.fn_trait_kind_from_lang_item(trait_def_id).is_some();
274         let gen_trait = tcx.require_lang_item(LangItem::Generator, cause_span);
275         let is_gen = gen_trait == trait_def_id;
276         if !is_fn && !is_gen {
277             debug!("deduce_sig_from_projection: not fn or generator");
278             return None;
279         }
280
281         if is_gen {
282             // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return`
283             // associated item and not yield.
284             let return_assoc_item = self.tcx.associated_item_def_ids(gen_trait)[1];
285             if return_assoc_item != projection.projection_def_id() {
286                 debug!("deduce_sig_from_projection: not return assoc item of generator");
287                 return None;
288             }
289         }
290
291         let input_tys = if is_fn {
292             let arg_param_ty = projection.skip_binder().projection_ty.substs.type_at(1);
293             let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty);
294             debug!("deduce_sig_from_projection: arg_param_ty={:?}", arg_param_ty);
295
296             match arg_param_ty.kind() {
297                 ty::Tuple(tys) => tys.into_iter().map(|k| k.expect_ty()).collect::<Vec<_>>(),
298                 _ => return None,
299             }
300         } else {
301             // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments,
302             // else they must have exactly 1 argument. For now though, just give up in this case.
303             return None;
304         };
305
306         // Since this is a return parameter type it is safe to unwrap.
307         let ret_param_ty = projection.skip_binder().term.ty().unwrap();
308         let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty);
309         debug!("deduce_sig_from_projection: ret_param_ty={:?}", ret_param_ty);
310
311         let sig = projection.rebind(self.tcx.mk_fn_sig(
312             input_tys.iter(),
313             &ret_param_ty,
314             false,
315             hir::Unsafety::Normal,
316             Abi::Rust,
317         ));
318         debug!("deduce_sig_from_projection: sig={:?}", sig);
319
320         Some(ExpectedSig { cause_span, sig })
321     }
322
323     fn sig_of_closure(
324         &self,
325         hir_id: hir::HirId,
326         expr_def_id: DefId,
327         decl: &hir::FnDecl<'_>,
328         body: &hir::Body<'_>,
329         expected_sig: Option<ExpectedSig<'tcx>>,
330     ) -> ClosureSignatures<'tcx> {
331         if let Some(e) = expected_sig {
332             self.sig_of_closure_with_expectation(hir_id, expr_def_id, decl, body, e)
333         } else {
334             self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body)
335         }
336     }
337
338     /// If there is no expected signature, then we will convert the
339     /// types that the user gave into a signature.
340     #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")]
341     fn sig_of_closure_no_expectation(
342         &self,
343         hir_id: hir::HirId,
344         expr_def_id: DefId,
345         decl: &hir::FnDecl<'_>,
346         body: &hir::Body<'_>,
347     ) -> ClosureSignatures<'tcx> {
348         let bound_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
349
350         self.closure_sigs(expr_def_id, body, bound_sig)
351     }
352
353     /// Invoked to compute the signature of a closure expression. This
354     /// combines any user-provided type annotations (e.g., `|x: u32|
355     /// -> u32 { .. }`) with the expected signature.
356     ///
357     /// The approach is as follows:
358     ///
359     /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations.
360     /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any.
361     ///   - If we have no expectation `E`, then the signature of the closure is `S`.
362     ///   - Otherwise, the signature of the closure is E. Moreover:
363     ///     - Skolemize the late-bound regions in `E`, yielding `E'`.
364     ///     - Instantiate all the late-bound regions bound in the closure within `S`
365     ///       with fresh (existential) variables, yielding `S'`
366     ///     - Require that `E' = S'`
367     ///       - We could use some kind of subtyping relationship here,
368     ///         I imagine, but equality is easier and works fine for
369     ///         our purposes.
370     ///
371     /// The key intuition here is that the user's types must be valid
372     /// from "the inside" of the closure, but the expectation
373     /// ultimately drives the overall signature.
374     ///
375     /// # Examples
376     ///
377     /// ```
378     /// fn with_closure<F>(_: F)
379     ///   where F: Fn(&u32) -> &u32 { .. }
380     ///
381     /// with_closure(|x: &u32| { ... })
382     /// ```
383     ///
384     /// Here:
385     /// - E would be `fn(&u32) -> &u32`.
386     /// - S would be `fn(&u32) ->
387     /// - E' is `&'!0 u32 -> &'!0 u32`
388     /// - S' is `&'?0 u32 -> ?T`
389     ///
390     /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`.
391     ///
392     /// # Arguments
393     ///
394     /// - `expr_def_id`: the `DefId` of the closure expression
395     /// - `decl`: the HIR declaration of the closure
396     /// - `body`: the body of the closure
397     /// - `expected_sig`: the expected signature (if any). Note that
398     ///   this is missing a binder: that is, there may be late-bound
399     ///   regions with depth 1, which are bound then by the closure.
400     #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")]
401     fn sig_of_closure_with_expectation(
402         &self,
403         hir_id: hir::HirId,
404         expr_def_id: DefId,
405         decl: &hir::FnDecl<'_>,
406         body: &hir::Body<'_>,
407         expected_sig: ExpectedSig<'tcx>,
408     ) -> ClosureSignatures<'tcx> {
409         // Watch out for some surprises and just ignore the
410         // expectation if things don't see to match up with what we
411         // expect.
412         if expected_sig.sig.c_variadic() != decl.c_variadic {
413             return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body);
414         } else if expected_sig.sig.skip_binder().inputs_and_output.len() != decl.inputs.len() + 1 {
415             return self.sig_of_closure_with_mismatched_number_of_arguments(
416                 expr_def_id,
417                 decl,
418                 body,
419                 expected_sig,
420             );
421         }
422
423         // Create a `PolyFnSig`. Note the oddity that late bound
424         // regions appearing free in `expected_sig` are now bound up
425         // in this binder we are creating.
426         assert!(!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST));
427         let bound_sig = expected_sig.sig.map_bound(|sig| {
428             let output = self.hide_parent_opaque_types(
429                 sig.output(),
430                 expected_sig.cause_span.unwrap_or(DUMMY_SP),
431                 body.id().hir_id,
432             );
433             self.tcx.mk_fn_sig(
434                 sig.inputs().iter().cloned(),
435                 output,
436                 sig.c_variadic,
437                 hir::Unsafety::Normal,
438                 Abi::RustCall,
439             )
440         });
441
442         // `deduce_expectations_from_expected_type` introduces
443         // late-bound lifetimes defined elsewhere, which we now
444         // anonymize away, so as not to confuse the user.
445         let bound_sig = self.tcx.anonymize_late_bound_regions(bound_sig);
446
447         let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig);
448
449         // Up till this point, we have ignored the annotations that the user
450         // gave. This function will check that they unify successfully.
451         // Along the way, it also writes out entries for types that the user
452         // wrote into our typeck results, which are then later used by the privacy
453         // check.
454         match self.check_supplied_sig_against_expectation(
455             hir_id,
456             expr_def_id,
457             decl,
458             body,
459             &closure_sigs,
460         ) {
461             Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok),
462             Err(_) => return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body),
463         }
464
465         closure_sigs
466     }
467
468     fn sig_of_closure_with_mismatched_number_of_arguments(
469         &self,
470         expr_def_id: DefId,
471         decl: &hir::FnDecl<'_>,
472         body: &hir::Body<'_>,
473         expected_sig: ExpectedSig<'tcx>,
474     ) -> ClosureSignatures<'tcx> {
475         let hir = self.tcx.hir();
476         let expr_map_node = hir.get_if_local(expr_def_id).unwrap();
477         let expected_args: Vec<_> = expected_sig
478             .sig
479             .skip_binder()
480             .inputs()
481             .iter()
482             .map(|ty| ArgKind::from_expected_ty(ty, None))
483             .collect();
484         let (closure_span, found_args) = match self.get_fn_like_arguments(expr_map_node) {
485             Some((sp, args)) => (Some(sp), args),
486             None => (None, Vec::new()),
487         };
488         let expected_span =
489             expected_sig.cause_span.unwrap_or_else(|| hir.span_if_local(expr_def_id).unwrap());
490         self.report_arg_count_mismatch(
491             expected_span,
492             closure_span,
493             expected_args,
494             found_args,
495             true,
496         )
497         .emit();
498
499         let error_sig = self.error_sig_of_closure(decl);
500
501         self.closure_sigs(expr_def_id, body, error_sig)
502     }
503
504     /// Enforce the user's types against the expectation. See
505     /// `sig_of_closure_with_expectation` for details on the overall
506     /// strategy.
507     fn check_supplied_sig_against_expectation(
508         &self,
509         hir_id: hir::HirId,
510         expr_def_id: DefId,
511         decl: &hir::FnDecl<'_>,
512         body: &hir::Body<'_>,
513         expected_sigs: &ClosureSignatures<'tcx>,
514     ) -> InferResult<'tcx, ()> {
515         // Get the signature S that the user gave.
516         //
517         // (See comment on `sig_of_closure_with_expectation` for the
518         // meaning of these letters.)
519         let supplied_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body);
520
521         debug!("check_supplied_sig_against_expectation: supplied_sig={:?}", supplied_sig);
522
523         // FIXME(#45727): As discussed in [this comment][c1], naively
524         // forcing equality here actually results in suboptimal error
525         // messages in some cases.  For now, if there would have been
526         // an obvious error, we fallback to declaring the type of the
527         // closure to be the one the user gave, which allows other
528         // error message code to trigger.
529         //
530         // However, I think [there is potential to do even better
531         // here][c2], since in *this* code we have the precise span of
532         // the type parameter in question in hand when we report the
533         // error.
534         //
535         // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706
536         // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796
537         self.infcx.commit_if_ok(|_| {
538             let mut all_obligations = vec![];
539
540             // The liberated version of this signature should be a subtype
541             // of the liberated form of the expectation.
542             for ((hir_ty, &supplied_ty), expected_ty) in iter::zip(
543                 iter::zip(
544                     decl.inputs,
545                     supplied_sig.inputs().skip_binder(), // binder moved to (*) below
546                 ),
547                 expected_sigs.liberated_sig.inputs(), // `liberated_sig` is E'.
548             ) {
549                 // Instantiate (this part of..) S to S', i.e., with fresh variables.
550                 let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
551                     hir_ty.span,
552                     LateBoundRegionConversionTime::FnCall,
553                     supplied_sig.inputs().rebind(supplied_ty),
554                 ); // recreated from (*) above
555
556                 // Check that E' = S'.
557                 let cause = self.misc(hir_ty.span);
558                 let InferOk { value: (), obligations } =
559                     self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?;
560                 all_obligations.extend(obligations);
561             }
562
563             let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars(
564                 decl.output.span(),
565                 LateBoundRegionConversionTime::FnCall,
566                 supplied_sig.output(),
567             );
568             let cause = &self.misc(decl.output.span());
569             let InferOk { value: (), obligations } = self
570                 .at(cause, self.param_env)
571                 .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?;
572             all_obligations.extend(obligations);
573
574             Ok(InferOk { value: (), obligations: all_obligations })
575         })
576     }
577
578     /// If there is no expected signature, then we will convert the
579     /// types that the user gave into a signature.
580     ///
581     /// Also, record this closure signature for later.
582     #[instrument(skip(self, decl, body), level = "debug")]
583     fn supplied_sig_of_closure(
584         &self,
585         hir_id: hir::HirId,
586         expr_def_id: DefId,
587         decl: &hir::FnDecl<'_>,
588         body: &hir::Body<'_>,
589     ) -> ty::PolyFnSig<'tcx> {
590         let astconv: &dyn AstConv<'_> = self;
591
592         trace!("decl = {:#?}", decl);
593         debug!(?body.generator_kind);
594
595         let bound_vars = self.tcx.late_bound_vars(hir_id);
596
597         // First, convert the types that the user supplied (if any).
598         let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a));
599         let supplied_return = match decl.output {
600             hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output),
601             hir::FnRetTy::DefaultReturn(_) => match body.generator_kind {
602                 // In the case of the async block that we create for a function body,
603                 // we expect the return type of the block to match that of the enclosing
604                 // function.
605                 Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => {
606                     debug!("closure is async fn body");
607                     self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(|| {
608                         // AFAIK, deducing the future output
609                         // always succeeds *except* in error cases
610                         // like #65159. I'd like to return Error
611                         // here, but I can't because I can't
612                         // easily (and locally) prove that we
613                         // *have* reported an
614                         // error. --nikomatsakis
615                         astconv.ty_infer(None, decl.output.span())
616                     })
617                 }
618
619                 _ => astconv.ty_infer(None, decl.output.span()),
620             },
621         };
622         let supplied_return =
623             self.hide_parent_opaque_types(supplied_return, decl.output.span(), body.id().hir_id);
624
625         let result = ty::Binder::bind_with_vars(
626             self.tcx.mk_fn_sig(
627                 supplied_arguments,
628                 supplied_return,
629                 decl.c_variadic,
630                 hir::Unsafety::Normal,
631                 Abi::RustCall,
632             ),
633             bound_vars,
634         );
635
636         debug!(?result);
637
638         let c_result = self.inh.infcx.canonicalize_response(result);
639         self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result);
640
641         result
642     }
643
644     fn hide_parent_opaque_types(&self, ty: Ty<'tcx>, span: Span, body_id: hir::HirId) -> Ty<'tcx> {
645         ty.fold_with(&mut ty::fold::BottomUpFolder {
646             tcx: self.infcx.tcx,
647             lt_op: |lt| lt,
648             ct_op: |ct| ct,
649             ty_op: |ty| match *ty.kind() {
650                 // Closures can't create hidden types for opaque types of their parent, as they
651                 // do not have all the outlives information available. Also `type_of` looks for
652                 // hidden types in the owner (so the closure's parent), so it would not find these
653                 // definitions.
654                 ty::Opaque(def_id, _substs)
655                     if matches!(
656                         self.infcx.opaque_type_origin(def_id, DUMMY_SP),
657                         Some(OpaqueTyOrigin::FnReturn(..))
658                     ) =>
659                 {
660                     let ty_var = self.next_ty_var(TypeVariableOrigin {
661                         kind: TypeVariableOriginKind::TypeInference,
662                         span,
663                     });
664                     let cause = ObligationCause::misc(span, body_id);
665                     self.register_predicates(vec![self.infcx.opaque_ty_obligation(
666                         ty,
667                         ty_var,
668                         true,
669                         self.param_env,
670                         cause,
671                     )]);
672                     ty_var
673                 }
674                 _ => ty,
675             },
676         })
677     }
678
679     /// Invoked when we are translating the generator that results
680     /// from desugaring an `async fn`. Returns the "sugared" return
681     /// type of the `async fn` -- that is, the return type that the
682     /// user specified. The "desugared" return type is an `impl
683     /// Future<Output = T>`, so we do this by searching through the
684     /// obligations to extract the `T`.
685     #[instrument(skip(self), level = "debug")]
686     fn deduce_future_output_from_obligations(&self, expr_def_id: DefId) -> Option<Ty<'tcx>> {
687         let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| {
688             span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn")
689         });
690
691         let ret_ty = ret_coercion.borrow().expected_ty();
692         let ret_ty = self.inh.infcx.shallow_resolve(ret_ty);
693         let (def_id, substs) = match *ret_ty.kind() {
694             ty::Opaque(def_id, substs) => (def_id, substs),
695             ty::Error(_) => return None,
696             _ => span_bug!(
697                 self.tcx.def_span(expr_def_id),
698                 "async fn generator return type not an inference variable"
699             ),
700         };
701
702         let item_bounds = self.tcx.explicit_item_bounds(def_id);
703
704         // Search for a pending obligation like
705         //
706         // `<R as Future>::Output = T`
707         //
708         // where R is the return type we are expecting. This type `T`
709         // will be our output.
710         let output_ty = item_bounds.iter().find_map(|&(predicate, span)| {
711             let bound_predicate = predicate.subst(self.tcx, substs).kind();
712             if let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder() {
713                 self.deduce_future_output_from_projection(
714                     span,
715                     bound_predicate.rebind(proj_predicate),
716                 )
717             } else {
718                 None
719             }
720         });
721
722         debug!("deduce_future_output_from_obligations: output_ty={:?}", output_ty);
723         output_ty
724     }
725
726     /// Given a projection like
727     ///
728     /// `<X as Future>::Output = T`
729     ///
730     /// where `X` is some type that has no late-bound regions, returns
731     /// `Some(T)`. If the projection is for some other trait, returns
732     /// `None`.
733     fn deduce_future_output_from_projection(
734         &self,
735         cause_span: Span,
736         predicate: ty::PolyProjectionPredicate<'tcx>,
737     ) -> Option<Ty<'tcx>> {
738         debug!("deduce_future_output_from_projection(predicate={:?})", predicate);
739
740         // We do not expect any bound regions in our predicate, so
741         // skip past the bound vars.
742         let predicate = match predicate.no_bound_vars() {
743             Some(p) => p,
744             None => {
745                 debug!("deduce_future_output_from_projection: has late-bound regions");
746                 return None;
747             }
748         };
749
750         // Check that this is a projection from the `Future` trait.
751         let trait_def_id = predicate.projection_ty.trait_def_id(self.tcx);
752         let future_trait = self.tcx.require_lang_item(LangItem::Future, Some(cause_span));
753         if trait_def_id != future_trait {
754             debug!("deduce_future_output_from_projection: not a future");
755             return None;
756         }
757
758         // The `Future` trait has only one associted item, `Output`,
759         // so check that this is what we see.
760         let output_assoc_item = self.tcx.associated_item_def_ids(future_trait)[0];
761         if output_assoc_item != predicate.projection_ty.item_def_id {
762             span_bug!(
763                 cause_span,
764                 "projecting associated item `{:?}` from future, which is not Output `{:?}`",
765                 predicate.projection_ty.item_def_id,
766                 output_assoc_item,
767             );
768         }
769
770         // Extract the type from the projection. Note that there can
771         // be no bound variables in this type because the "self type"
772         // does not have any regions in it.
773         let output_ty = self.resolve_vars_if_possible(predicate.term);
774         debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty);
775         // This is a projection on a Fn trait so will always be a type.
776         Some(output_ty.ty().unwrap())
777     }
778
779     /// Converts the types that the user supplied, in case that doing
780     /// so should yield an error, but returns back a signature where
781     /// all parameters are of type `TyErr`.
782     fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> {
783         let astconv: &dyn AstConv<'_> = self;
784
785         let supplied_arguments = decl.inputs.iter().map(|a| {
786             // Convert the types that the user supplied (if any), but ignore them.
787             astconv.ast_ty_to_ty(a);
788             self.tcx.ty_error()
789         });
790
791         if let hir::FnRetTy::Return(ref output) = decl.output {
792             astconv.ast_ty_to_ty(&output);
793         }
794
795         let result = ty::Binder::dummy(self.tcx.mk_fn_sig(
796             supplied_arguments,
797             self.tcx.ty_error(),
798             decl.c_variadic,
799             hir::Unsafety::Normal,
800             Abi::RustCall,
801         ));
802
803         debug!("supplied_sig_of_closure: result={:?}", result);
804
805         result
806     }
807
808     fn closure_sigs(
809         &self,
810         expr_def_id: DefId,
811         body: &hir::Body<'_>,
812         bound_sig: ty::PolyFnSig<'tcx>,
813     ) -> ClosureSignatures<'tcx> {
814         let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, bound_sig);
815         let liberated_sig = self.inh.normalize_associated_types_in(
816             body.value.span,
817             body.value.hir_id,
818             self.param_env,
819             liberated_sig,
820         );
821         ClosureSignatures { bound_sig, liberated_sig }
822     }
823 }