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