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