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