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